code
stringlengths
10
1.34M
language
stringclasses
1 value
// +build OMIT package main import "fmt" // prime returns true if n is a prime number. func prime(n int) bool { for i := 2; i < n; i++ { if n%i == 0 { return false } } return true } // primes returns a channel of ints on which it writes the first n prime // numbers before closing it. func primes(n int) ch...
Go
// +build OMIT package main import ( "fmt" "strings" ) type Name struct { First string Middle string Last string } func (n Name) String() string { return fmt.Sprintf("%s %c. %s", n.First, n.Middle[0], strings.ToUpper(n.Last)) } type SimpleName string func (s SimpleName) String() string { return string(s)...
Go
// +build OMIT package main import ( "bytes" "net" ) func handleConn(conn net.Conn) { // does something that should be tested. } type loopBack struct { net.Conn buf bytes.Buffer } func (c *loopBack) Read(b []byte) (int, error) { return c.buf.Read(b) } func (c *loopBack) Write(b []byte) (int, error) { retur...
Go
// +build OMIT package main import ( "fmt" "time" ) func f(left, right chan int) { left <- 1 + <-right } func main() { start := time.Now() const n = 1000 leftmost := make(chan int) right := leftmost left := leftmost for i := 0; i < n; i++ { right = make(chan int) go f(left, right) left = right } ...
Go
// +build OMIT package main import "fmt" type Person struct{ Name string } func (p Person) Introduce() { fmt.Println("Hi, I'm", p.Name) } type Employee struct { Person EmployeeID int } func ExampleEmployee() { var e Employee e.Name = "Peter" e.EmployeeID = 1234 e.Introduce() }
Go
// +build OMIT package main import ( "fmt" "time" ) func sleepAndTalk(t time.Duration, msg string) { time.Sleep(t) fmt.Printf("%v ", msg) } func main() { sleepAndTalk(0*time.Second, "Hello") sleepAndTalk(1*time.Second, "Gophers!") sleepAndTalk(2*time.Second, "What's") sleepAndTalk(3*time.Second, "up?") }
Go
// +build OMIT package main import ( "fmt" "net/http" ) var nextID = make(chan int) func handler(w http.ResponseWriter, q *http.Request) { fmt.Fprintf(w, "<h1>You got %v<h1>", <-nextID) } func main() { http.HandleFunc("/next", handler) go func() { for i := 0; ; i++ { nextID <- i } }() http.ListenAndS...
Go
// Package runner provides a Runner type that is used to define both RunCounter // and EmbeddedRunCounter to show examples of how to use composition in Go. package runner import "fmt" // A Task is a simple task that prints a message when run. type Task struct{ Msg string } func (t Task) Run() { fmt.Println("running...
Go
package runner // RunCounter2 is completely equivalent to RunCounter, // but uses struct embedding to avoid the boilerplate of redeclaring // the Name method. type RunCounter2 struct { Runner // HL count int } func NewRunCounter2(name string) *RunCounter2 { return &RunCounter2{Runner{name}, 0} } func (r *RunCoun...
Go
// +build OMIT package main import ( "fmt" "time" ) func sleepAndTalk(t time.Duration, msg string) { time.Sleep(t) fmt.Printf("%v ", msg) } func main() { go sleepAndTalk(0*time.Second, "Hello") go sleepAndTalk(1*time.Second, "Gophers!") go sleepAndTalk(2*time.Second, "What's") go sleepAndTalk(3*time.Second,...
Go
// +build OMIT package main import ( "bytes" "fmt" "io" "os" ) var ( _ = bytes.Buffer{} _ = os.Stdout ) // WriteCounter tracks the total number of bytes written. type WriteCounter struct { io.ReadWriter count int } func (w *WriteCounter) Write(b []byte) (int, error) { w.count += len(b) return w.ReadWrite...
Go
// +build OMIT package main import ( "fmt" "time" ) func sleepAndTalk(t time.Duration, msg string) { time.Sleep(t) fmt.Printf("%v ", msg) } func main() { go sleepAndTalk(0*time.Second, "Hello") go sleepAndTalk(1*time.Second, "Gophers!") go sleepAndTalk(2*time.Second, "What's") go sleepAndTalk(3*time.Second,...
Go
// +build OMIT package main import ( "fmt" "time" ) func sleepAndTalk(secs time.Duration, msg string, c chan string) { time.Sleep(secs * time.Second) c <- msg } func main() { c := make(chan string) go sleepAndTalk(0, "Hello", c) go sleepAndTalk(1, "Gophers!", c) go sleepAndTalk(2, "What's", c) go sleepAnd...
Go
// +build OMIT package main import ( "fmt" "net/http" ) var battle = make(chan string) func handler(w http.ResponseWriter, q *http.Request) { select { case battle <- q.FormValue("usr"): fmt.Fprintf(w, "You won!") case won := <-battle: fmt.Fprintf(w, "You lost, %v is better than you", won) } } func main()...
Go
// +build ignore,OMIT package main import "fmt" func main() { fmt.Printf("hello, world\n"); }
Go
// +build ignore,OMIT package main import "fmt" // Send the sequence 2, 3, 4, ... to channel 'ch'. func generate(ch chan<- int) { for i := 2; ; i++ { ch <- i; // Send 'i' to channel 'ch'. } } // Copy the values from channel 'in' to channel 'out', // removing those divisible by 'prime'. func filter(src <-chan in...
Go
// +build ignore,OMIT package main // Send the sequence 2, 3, 4, ... to channel 'ch'. func Generate(ch *chan <- int) { for i := 2; ; i++ { ch <- i // Send 'i' to channel 'ch'. } } // Copy the values from channel 'in' to channel 'out', // removing those divisible by 'prime'. func Filter(in *chan <- int, out *<-c...
Go
// +build ignore,OMIT package main // Send the sequence 2, 3, 4, ... to channel 'ch'. func Generate(ch *chan-< int) { for i := 2; ; i++ { ch -< i // Send 'i' to channel 'ch'. } } // Copy the values from channel 'in' to channel 'out', // removing those divisible by 'prime'. func Filter(in *chan<- int, out *chan-<...
Go
// +build ignore,OMIT package Main // Send the sequence 2, 3, 4, ... to channel 'ch'. func Generate(ch *chan> int) { for i := 2; ; i++ { >ch = i; // Send 'i' to channel 'ch'. } } // Copy the values from channel 'in' to channel 'out', // removing those divisible by 'prime'. func Filter(in *chan< int, out *chan> i...
Go
// +build ignore,OMIT package main import "fmt" func main() { fmt.Printf("Hello, gophers!\n") }
Go
// +build ignore,OMIT package main import "fmt" // Send the sequence 2, 3, 4, … to channel 'ch'. func generate(ch chan<- int) { for i := 2; ; i++ { ch <- i // Send 'i' to channel 'ch'. } } // Copy the values from channel 'src' to channel 'dst', // removing those divisible by 'prime'. func filter(src <-chan int...
Go
// +build ignore,OMIT package main func main() int { print "hello, world\n"; return 0; }
Go
// +build ignore,OMIT package main func main() { print("hello, world\n"); }
Go
// +build ignore,OMIT package main import "fmt" func main() { fmt.printf("hello, world\n"); }
Go
// +build ignore,OMIT package main // Send the sequence 2, 3, 4, ... to channel 'ch'. func Generate(ch chan <- int) { for i := 2; ; i++ { ch <- i // Send 'i' to channel 'ch'. } } // Copy the values from channel 'in' to channel 'out', // removing those divisible by 'prime'. func Filter(in chan <- int, out *<-cha...
Go
// +build ignore,OMIT package main import "fmt" func main() { fmt.Printf("hello, world\n") }
Go
// +build ignore,OMIT package main import "fmt" func main() { fmt.Println("Hello, Gophers (some of whom know 日本語)!") }
Go
// +build ignore,OMIT package main func main() { print "hello, world\n"; }
Go
package main import "fmt" func main() { fmt.Println("Hello, world!") }
Go
// +build ignore package main import ( "fmt" "go/ast" "go/parser" "go/token" ) func main() { src := ` package http type Handler interface { ServeHTTP(ResponseWriter, *Request) } ` f, _ := parser.ParseFile(token.NewFileSet(), "", src, 0) typ := f.Decls[0].(*ast.GenDecl).Specs[0].(*ast.TypeSpec).Type.(*ast.Int...
Go
// +build ignore package main import ( "fmt" "go/ast" "go/parser" "go/token" ) func main() { src := `package hack; import "net/http"; var i http.Handler` f, _ := parser.ParseFile(token.NewFileSet(), "", src, 0) decl := f.Decls[1].(*ast.GenDecl) // var i http.Handler spec := decl.Specs[0].(*ast.ValueSpe...
Go
// +build ignore package main import ( "os" "text/template" ) func main() { const stub = "func ({{.Recv}}) {{.Name}}" + "({{range .Params}}{{.Name}} {{.Type}}, {{end}})" + "({{range .Res}}{{.Name}} {{.Type}}, {{end}})" + "{\n}\n\n" tmpl := template.Must(template.New("test").Parse(stub)) m := Method{ Re...
Go
// +build ignore package main import ( "fmt" "code.google.com/p/go.tools/imports" ) func main() { iface := "http.Handler" src := "package hack; var i " + iface // HL fmt.Println(src, "\n---") imp, _ := imports.Process("", []byte(src), nil) // HL // ignoring errors throughout this presentation fmt.Println(s...
Go
// +build ignore package main // Method represents a method signature. type Method struct { Recv string Func } // Func represents a function signature. type Func struct { Name string Params []Param Res []Param } // Param represents a parameter in a function or method signature. type Param struct { Name s...
Go
// +build ignore package main import ( "fmt" "go/parser" "go/token" "strconv" ) func main() { src := `package hack; import "net/http"; var i http.Handler` fset := token.NewFileSet() f, _ := parser.ParseFile(fset, "", src, 0) raw := f.Imports[0].Path.Value path, _ := strconv.Unquote(raw) fmt.Println(raw, ...
Go
// +build ignore package main import ( "fmt" "go/format" ) func main() { ugly := `func (f *File) Read(p []byte, )(n int, err error, ){}` fmt.Println(ugly) pretty, _ := format.Source([]byte(ugly)) // HL fmt.Println(string(pretty)) }
Go
// +build ignore package main import ( "go/ast" "go/build" "go/parser" "go/printer" "go/token" "os" "path/filepath" ) func main() { fset, files := parsePackage("net/http") id := "Handler" for _, f := range files { for _, decl := range f.Decls { decl, ok := decl.(*ast.GenDecl) if !ok || decl.Tok !=...
Go
// +build ignore package main import ( "fmt" "go/build" ) func main() { pkg, _ := build.Import("net/http", "", 0) // HL fmt.Println(pkg.Dir) fmt.Println(pkg.GoFiles) }
Go
// +build OMIT package main import ( "fmt" "code.google.com/p/go-tour/tree" ) func Walk(t *tree.Tree) { if t.Left != nil { Walk(t.Left) } fmt.Println(t.Value) if t.Right != nil { Walk(t.Right) } } func main() { Walk(tree.New(1)) }
Go
// +build OMIT package main import ( "fmt" "sort" ) type Organ struct { Name string Weight Grams } func (o *Organ) String() string { return fmt.Sprintf("%v (%v)", o.Name, o.Weight) } type Grams int func (g Grams) String() string { return fmt.Sprintf("%dg", int(g)) } // PART1 OMIT type Organs []*Organ fun...
Go
// +build OMIT package main import ( "fmt" "io" "log" ) // ByteReader implements an io.Reader that emits a stream of its byte value. type ByteReader byte func (b ByteReader) Read(buf []byte) (int, error) { for i := range buf { buf[i] = byte(b) } return len(buf), nil } type LogReader struct { io.Reader } ...
Go
// +build OMIT package main import ( "fmt" "code.google.com/p/go-tour/tree" ) func Walk(root *tree.Tree, quit chan struct{}) chan int { ch := make(chan int) go func() { walk(root, ch, quit) close(ch) }() return ch } func walk(t *tree.Tree, ch chan int, quit chan struct{}) { if t.Left != nil { walk(t.L...
Go
// +build OMIT package main import ( "fmt" "code.google.com/p/go-tour/tree" ) func Walk(root *tree.Tree) chan int { ch := make(chan int) go func() { walk(root, ch) close(ch) }() return ch } func walk(t *tree.Tree, ch chan int) { if t.Left != nil { walk(t.Left, ch) } ch <- t.Value if t.Right != nil ...
Go
// +build OMIT package main import ( "fmt" "code.google.com/p/go-tour/tree" ) func Walk(root *tree.Tree) *Walker { return &Walker{stack: []*frame{{t: root}}} } type Walker struct { stack []*frame } type frame struct { t *tree.Tree pc int } func (w *Walker) Next() (int, bool) { if len(w.stack) == 0 { re...
Go
// +build OMIT package main import ( "fmt" "sort" ) type Organ struct { Name string Weight Grams } func (o *Organ) String() string { return fmt.Sprintf("%v (%v)", o.Name, o.Weight) } type Grams int func (g Grams) String() string { return fmt.Sprintf("%dg", int(g)) } type Organs []*Organ func (s Organs) Le...
Go
// +build OMIT package main import ( "io" "io/ioutil" "log" ) // ByteReader implements an io.Reader that emits a stream of its byte value. type ByteReader byte func (b ByteReader) Read(buf []byte) (int, error) { for i := range buf { buf[i] = byte(b) } return len(buf), nil } type LogReader struct { io.Read...
Go
// +build OMIT package main import "fmt" type Organ struct { Name string Weight Grams } func (o *Organ) String() string { return fmt.Sprintf("%v (%v)", o.Name, o.Weight) } type Grams int func (g Grams) String() string { return fmt.Sprintf("%dg", int(g)) } func main() { s := []*Organ{{"brain", 1340}, {"heart...
Go
// +build OMIT package main import ( "fmt" "sort" ) type IntSlice []int func (p IntSlice) Len() int { return len(p) } func (p IntSlice) Less(i, j int) bool { return p[i] < p[j] } func (p IntSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] } func main() { // START OMIT s := []int{7, 5, 3, 11, 2} ...
Go
package subprocess import ( "fmt" "os" ) func Crasher() { fmt.Println("Going down in flames!") os.Exit(1) }
Go
// +build OMIT package main import ( "fmt" "log" "net/http" "net/http/httptest" ) func main() { // START OMIT handler := func(w http.ResponseWriter, r *http.Request) { http.Error(w, "something failed", http.StatusInternalServerError) } req, err := http.NewRequest("GET", "http://example.com/foo", nil) if ...
Go
// +build OMIT package main import ( "fmt" "io/ioutil" "log" "net/http" "net/http/httptest" ) func main() { // START OMIT ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, "Hello, client") })) defer ts.Close() res, err := http.Get(ts.URL) if err !=...
Go
// +build OMIT package main import ( "fmt" "go/ast" "go/parser" "go/token" "io/ioutil" "path/filepath" "runtime" "sort" "strings" "time" ) func walk(dir string, f func(string) bool) bool { fis, err := ioutil.ReadDir(dir) if err != nil { panic(err) } // parse all *.go files in directory; // traverse ...
Go
// +build OMIT package main // idents.go import ( "fmt" "os" "text/scanner" ) func main() { var s scanner.Scanner s.Init(os.Stdin) for { switch s.Scan() { case scanner.EOF: return // all done case scanner.Ident: fmt.Println(s.TokenText()) } } }
Go
// +build OMIT package main import ( "fmt" "go/ast" "go/parser" "go/token" "io/ioutil" "path/filepath" "runtime" "sort" "strings" "time" ) func walk(dir string, f func(string) bool) bool { fis, err := ioutil.ReadDir(dir) if err != nil { panic(err) } // parse all *.go files in directory; // traverse ...
Go
// +build OMIT package main import "fmt" // Point START OMIT type Point struct { x, y int } // Point END OMIT // String START OMIT func (p Point) String() string { return fmt.Sprintf("(%d, %d)", p.x, p.y) } // String END OMIT // main START OMIT func main() { p := Point{2, 3} fmt.Println(p.String()) fmt.Prin...
Go
// +build OMIT package main import "fmt" // type START OMIT type Weekday int // type END OMIT const ( Mon Weekday = iota Tue Wed Thu Fri Sat Sun ) var names = [...]string{"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"} // String START OMIT func (d Weekday) String() string { /...
Go
// +build OMIT package examples // IndexOfAny START OMIT func IndexOfAny(str string, chars []rune) int { if len(str) == 0 || len(chars) == 0 { return -1 } for i, ch := range str { for _, match := range chars { if ch == match { return i } } } return -1 } // IndexOfAny END OMIT
Go
// +build OMIT package main import ( "fmt" "time" ) // f START OMIT func f(msg string, delay time.Duration, ch chan string) { for { ch <- msg time.Sleep(delay) } } // f END OMIT // main START OMIT func main() { ch := make(chan string) go f("A--", 300*time.Millisecond, ch) go f("-B-", 500*time.Millisecon...
Go
// +build OMIT package main import ( "fmt" "io/ioutil" "path/filepath" "runtime" "strings" ) func walk(dir string, f func(string) bool) bool { fis, err := ioutil.ReadDir(dir) if err != nil { panic(err) } // parse all *.go files in directory; // traverse subdirectories, but don't walk into testdata for _...
Go
// +build OMIT package main import ( "fmt" "go/ast" "go/parser" "go/token" "io/ioutil" "path/filepath" "runtime" "strings" ) func walk(dir string, f func(string) bool) bool { fis, err := ioutil.ReadDir(dir) if err != nil { panic(err) } // parse all *.go files in directory; // traverse subdirectories, ...
Go
// +build OMIT package main import ( "fmt" "time" ) // f START OMIT func f(msg string, delay time.Duration) { for { fmt.Println(msg) time.Sleep(delay) } } // f END OMIT // main START OMIT func main() { go f("A--", 300*time.Millisecond) go f("-B-", 500*time.Millisecond) go f("--C", 1100*time.Millisecond)...
Go
// +build OMIT package main import "fmt" func main() { fmt.Println("Hello, 世界!") }
Go
package main import ( "fmt" "log" "net/http" ) func HelloServer(w http.ResponseWriter, req *http.Request) { log.Println(req.URL) fmt.Fprintf(w, "Hello, 世界!\nURL = %s\n", req.URL) } func main() { fmt.Println("please connect to localhost:7777/hello") http.HandleFunc("/hello", HelloServer) log.Fatal(http.Listen...
Go
// +build OMIT package main import "fmt" type Point struct { x, y int } func (p Point) String() string { return fmt.Sprintf("(%d, %d)", p.x, p.y) } type Weekday int const ( Mon Weekday = iota Tue Wed Thu Fri Sat Sun ) var names = [...]string{"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Satur...
Go
// +build OMIT package main import ( "fmt" "sort" ) type Weekday int const ( Mon Weekday = iota Tue Wed Thu Fri Sat Sun ) var names = [...]string{"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"} func (d Weekday) String() string { // ... return names[d] } // lexical START OM...
Go
// +build OMIT package main import ( "fmt" "time" ) func main() { start := time.Now() fmt.Println(start) for i := 0; i < 10; i++ { time.Sleep(time.Nanosecond) fmt.Println(time.Since(start)) } }
Go
// +build OMIT package main import ( "fmt" "time" ) func main() { fmt.Println("Good night") time.Sleep(8 * time.Hour) fmt.Println("Good morning") }
Go
// +build OMIT package main import ( "log" "os/exec" ) func main() { err := exec.Command("mkdir", "/tmp/foo").Run() if err != nil { log.Fatal(err) } err = exec.Command("rm", "-rf", "/tmp/foo").Run() if err != nil { log.Fatal(err) } }
Go
// +build OMIT package main func main() { for { } }
Go
// +build OMIT package main import ( "fmt" "io/ioutil" "log" ) func main() { const filename = "/tmp/file.txt" err := ioutil.WriteFile(filename, []byte("Hello, file system\n"), 0644) if err != nil { log.Fatal(err) } b, err := ioutil.ReadFile(filename) if err != nil { log.Fatal(err) } fmt.Printf("%s"...
Go
// +build OMIT package main import ( "log" "os" ) func main() { err := os.RemoveAll("/foo") if err != nil { log.Fatal(err) } }
Go
// +build OMIT package main func foo(a [1000]byte) { foo(a) } func main() { foo([1000]byte{}) }
Go
// +build OMIT package main type list struct { buf [100000]byte next *list } func main() { var l *list for { l = &list{next: l} } }
Go
// +build OMIT package main import ( "io" "log" "net" "os" ) func main() { l, err := net.Listen("tcp", "127.0.0.1:4000") if err != nil { log.Fatal(err) } defer l.Close() go dial() c, err := l.Accept() if err != nil { log.Fatal(err) } defer c.Close() io.Copy(os.Stdout, c) } func dial() { c, err...
Go
// +build OMIT package main import "fmt" func main() { fmt.Println("Hello, gophers!") }
Go
// +build OMIT package main import ( "encoding/json" "fmt" "log" "net/http" ) func main() { res, err := http.Get("http://api.openweathermap.org/data/2.5/weather?q=Portland") if err != nil { log.Fatal(err) } defer res.Body.Close() var w struct { Weather []struct { Desc string `json:"description"` }...
Go
// +build OMIT package main func main() { c := make(chan int) <-c }
Go
// +build ignore package main import ( "fmt" "os" ) // 1 START OMIT var V = struct { name string os.FileMode }{ name: "hello.go", } func main() { fmt.Println(V) } // 1 END OMIT
Go
// +build ignore package main import "fmt" // 1 START OMIT const C1 = 1e-323 const C2 = C1 / 100 const C3 = C2 * 100 const C4 float64 = C1 / 100 const C5 = C4 * 100 func main() { fmt.Println(C3, C5) } // 1 END OMIT
Go
// +build ignore package main import "fmt" // 2 START OMIT // 1 START OMIT func main() { i := 1 f := func() T { return T{ i: 1, // HL } } fmt.Println(i, f()) } // 1 END OMIT type T struct{ i int } // 2 END OMIT
Go
// +build ignore package main import "fmt" // 1 START OMIT const C1 = 1e+308 const C2 = C1 * 10 const C3 = C2 / 10 var V1 = C1 var V2 = V1 * 10 var V3 = V2 / 10 func main() { fmt.Println(C3, V3) } // 1 END OMIT
Go
// +build ignore package main import ( "fmt" "runtime" ) // 1 START OMIT type P *P type S []S type C chan C type M map[int]M // 1 END OMIT // 2 START OMIT func Val(p *P) int { if p == nil { return 0 } else { return 1 + Val(*p) } } func Add(a, b *P) *P { if b == nil { return a } else { a1 := new(P) ...
Go
// +build ignore package main import "fmt" // 1 START OMIT type F func(*State) F type State int func Begin(s *State) F { *s = 1 return Middle } func Middle(s *State) F { *s++ if *s >= 10 { return End } return Middle } // 1 END OMIT // 2 START OMIT func End(s *State) F { fmt.Println(*s) return nil } fu...
Go
// +build ignore package main import ( "fmt" "unsafe" ) // 1 START OMIT var V1 = 0x01020304 var V2 [unsafe.Sizeof(V1)]byte func main() { *(*int)(unsafe.Pointer(&V2)) = V1 fmt.Println(V2) } // 1 END OMIT
Go
// +build ignore package main import "fmt" // 2 START OMIT // 1 START OMIT func main() { i := 1 f := func() T { return T{ i: 1, // HL } } fmt.Println(i, f()) } // 1 END OMIT type T map[int]int // 2 END OMIT
Go
// +build OMIT package main import ( "fmt" "math/rand" "time" ) // START1 OMIT func main() { c := fanIn(boring("Joe"), boring("Ann")) // HL for i := 0; i < 10; i++ { fmt.Println(<-c) // HL } fmt.Println("You're both boring; I'm leaving.") } // STOP1 OMIT // START2 OMIT func boring(msg string) <-chan string...
Go
// +build OMIT package main import ( "fmt" "time" "math/rand" ) func waiter(i int, block, done chan struct{}) { time.Sleep(time.Duration(rand.Intn(3000)) * time.Millisecond) fmt.Println(i, "waiting...") <-block // HL fmt.Println(i, "done!") done <- struct{}{} } func main() { block, done := make(chan struct...
Go
// +build OMIT package main import ( "fmt" "math/rand" "time" ) func worker(i int, ch chan Work, quit chan struct{}) { for { select { case w := <-ch: if quit == nil { // HL w.Refuse(); fmt.Println("worker", i, "refused", w) break } w.Do(); fmt.Println("worker", i, "processed", w) case <-qu...
Go
// +build OMIT package main import "fmt" var battle = make(chan string) func warrior(name string, done chan struct{}) { select { case opponent := <-battle: fmt.Printf("%s beat %s\n", name, opponent) case battle <- name: // I lost :-( } done <- struct{}{} } func main() { done := make(chan struct{}) langs...
Go
// +build OMIT package main import ( "fmt" "math/rand" "time" ) func worker(i int, ch chan Work, quit chan struct{}) { var quitting bool for { select { case w := <-ch: if quitting { w.Refuse(); fmt.Println("worker", i, "refused", w) break } w.Do(); fmt.Println("worker", i, "processed", w) ...
Go
// +build OMIT package main import ( "fmt" "time" ) func main() { // START OMIT t := time.Now() fmt.Println(t.In(time.UTC)) home, _ := time.LoadLocation("Australia/Sydney") fmt.Println(t.In(home)) // END OMIT }
Go
// +build OMIT package main import ( "fmt" "time" ) func main() { // START OMIT if time.Now().Hour() < 12 { fmt.Println("Good morning.") } else { fmt.Println("Good afternoon (or evening).") } // END OMIT }
Go
// +build OMIT package main import ( "encoding/json" "fmt" "strings" ) const blob = `[ {"Title":"Øredev", "URL":"http://oredev.org"}, {"Title":"Strange Loop", "URL":"http://thestrangeloop.com"} ]` type Item struct { Title string URL string } func main() { var items []*Item json.NewDecoder(strings.NewRea...
Go
// +build OMIT package main import ( "compress/gzip" "encoding/base64" "io" "os" "strings" ) func main() { var r io.Reader r = strings.NewReader(data) r = base64.NewDecoder(base64.StdEncoding, r) r, _ = gzip.NewReader(r) io.Copy(os.Stdout, r) } const data = ` H4sIAAAJbogA/1SOO5KDQAxE8zlFZ5tQXGCjjfYIjoURoP...
Go
// +build OMIT // This is a somewhat cut back version of webfront, available at // http://github.com/nf/webfront /* Copyright 2011 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at ...
Go
// +build OMIT package main import "strings" import "testing" func TestToUpper(t *testing.T) { in := "loud noises" want := "LOUD NOISES" got := strings.ToUpper(in) if got != want { t.Errorf("ToUpper(%v) = %v, want %v", in, got, want) } } func TestContains(t *testing.T) { var tests = []struct { str, subst...
Go
// +build OMIT package main import ( "fmt" "log" "net/http" ) type Greeting string func (g Greeting) ServeHTTP(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, g) } func main() { err := http.ListenAndServe("localhost:4000", Greeting("Hello, go")) if err != nil { log.Fatal(err) } }
Go
// +build OMIT package main import "fmt" func main() { fmt.Println("Hello, go") }
Go
// +build OMIT package main import ( "flag" "fmt" "time" ) var ( message = flag.String("message", "Hello!", "what to say") delay = flag.Duration("delay", 2*time.Second, "how long to wait") ) func main() { flag.Parse() fmt.Println(*message) time.Sleep(*delay) }
Go
// +build OMIT package io type Writer interface { Write(p []byte) (n int, err error) } type Reader interface { Read(p []byte) (n int, err error) }
Go