package main import "fmt" func main() { v := 42 // change me! fmt.Printf("v is of type %T\n", v) } //----- package main import "fmt" func main() { sum := 0 for i := 0; i < 10; i++ { sum += i } fmt.Println(sum) sum := 1 for ; sum < 1000; { sum += sum } fmt.Println(sum) sum := 1 for sum < 1000 { // same as while sum += sum } fmt.Println(sum) } //----- package main import ("golang.org/x/tour/tree" "fmt" ) // Walk walks the tree t sending all values // from the tree to the channel ch. func Walk(t *tree.Tree, ch chan int) { ch <- t.Value if (t.Left != nil) { Walk(t.Left,ch) } if (t.Right != nil) { Walk(t.Right,ch) } } // Same determines whether the trees // t1 and t2 contain the same values. func Same(t1, t2 *tree.Tree) bool { ch1 :=make(chan int, 1000) ch2 :=make(chan int, 1000) go Walk(t1, ch1) go Walk(t2, ch2) issame := true for i:=0; i<10; i++ { if (<-ch1 != <-ch2) { issame = false break } } return issame } func main() { t1 := tree.New(1) t2 := tree.New(1) fmt.Printf("%v",Same(t1,t2)) } //---- package main import ( "fmt" "math" ) func pow(x, n, lim float64) float64 { if v := math.Pow(x, n); v < lim { return v } return lim } func main() { fmt.Println( pow(3, 2, 10), pow(3, 3, 20), ) } //---- package main import ( "fmt" "runtime" ) func main() { fmt.Print("Go runs on ") switch os := runtime.GOOS; os { case "darwin": fmt.Println("OS X.") case "linux": fmt.Println("Linux.") default: // freebsd, openbsd, // plan9, windows... fmt.Printf("%s.\n", os) } } //----- package main import "fmt" func main() { fmt.Println("counting") for i := 0; i < 10; i++ { defer fmt.Println(i) // last in first out } fmt.Println("done") } //---- package main import "fmt" func main() { var a [2]string a[0] = "Hello" a[1] = "World" fmt.Println(a[0], a[1]) fmt.Println(a) primes := [6]int{2, 3, 5, 7, 11, 13} fmt.Println(primes) } //----- func main() { a := make([]int, 5) printSlice("a", a) b := make([]int, 0, 5) printSlice("b", b) c := b[:2] printSlice("c", c) d := c[2:5] printSlice("d", d) } //---- func main() { var s []int printSlice(s) // append works on nil slices. s = append(s, 0) printSlice(s) // The slice grows as needed. s = append(s, 1) printSlice(s) // We can add more than one element at a time. s = append(s, 2, 3, 4) printSlice(s) } //--- func main() { var s []int printSlice(s) // append works on nil slices. s = append(s, 0) printSlice(s) // The slice grows as needed. s = append(s, 1) printSlice(s) // We can add more than one element at a time. s = append(s, 2, 3, 4) printSlice(s) } //--- func main() { var s []int printSlice(s) // append works on nil slices. s = append(s, 0) printSlice(s) // The slice grows as needed. s = append(s, 1) printSlice(s) // We can add more than one element at a time. s = append(s, 2, 3, 4) printSlice(s) } //---- package main import "fmt" var pow = []int{1, 2, 4, 8, 16, 32, 64, 128} func main() { for i, v := range pow { fmt.Printf("2**%d = %d\n", i, v) } } //---- package main import "fmt" func main() { pow := make([]int, 10) for i := range pow { pow[i] = 1 << uint(i) // == 2**i } for _, value := range pow { fmt.Printf("%d\n", value) } } //---- package main import "golang.org/x/tour/pic" func Pic(dx, dy int) [][]uint8 { var pic [][] uint8 = make([][] uint8,dx); for i:=0;i<dx;i++{ pic [i] = make ([] uint8,dy) for j:=0;j<dy;j++{ pic[i][j]=uint8(i*j) } } return pic } func main() { pic.Show(Pic) } //---- package main import ( "golang.org/x/tour/wc" "fmt" "strings" ) func WordCount(s string) map[string]int { var m map[string]int=make(map[string]int) for _,v := range strings.Fields(s) { m[v]=m[v]+1 } return m } func main() { fmt.Printf("%d",WordCount("hello hello world")["hello"]) wc.Test(WordCount) } //---- package main import ( "fmt" "math" ) func compute(fn func(float64, float64) float64) float64 { return fn(3, 4) } func main() { hypot := func(x, y float64) float64 { return math.Sqrt(x*x + y*y) } fmt.Println(hypot(5, 12)) fmt.Println(compute(hypot)) fmt.Println(compute(math.Pow)) }
//---
Function Closure
A closure is a function value that references variables from outside its body.
package main import "fmt" func adder() func(int) int { sum := 0 return func(x int) int { sum += x return sum } } func main() { pos, neg := adder(), adder() for i := 0; i < 10; i++ { fmt.Println( pos(i), neg(-2*i), ) } } //----- package main import "fmt" // fibonacci is a function that returns // a function that returns an int. func fibonacci() func() int { b,c := 0,1 var t,a int return func() int{ t = c+b a = b b = c c = t return a } } func main() { f := fibonacci() for i := 0; i < 10; i++ { fmt.Println(f()) } } //---- package main import ( "fmt" "math" ) type Vertex struct { X, Y float64 } func (v Vertex) Abs() float64 { return math.Sqrt(v.X*v.X + v.Y*v.Y) } func AbsFunc(v Vertex) float64 { return math.Sqrt(v.X*v.X + v.Y*v.Y) } func main() { v := Vertex{3, 4} fmt.Println(v.Abs()) fmt.Println(AbsFunc(v)) p := &Vertex{4, 3} fmt.Println(p.Abs()) fmt.Println(AbsFunc(*p)) } //---- package main import "fmt" type I interface { M() } type T struct { S string } // This method means type T implements the interface I, // but we don't need to explicitly declare that it does so. func (t T) M() { fmt.Println(t.S) } func main() { var i I = T{"hello"} i.M() } //--- package main import ( "fmt" "math" ) type I interface { M() } type T struct { S string } func (t *T) M() { fmt.Println(t.S) } type F float64 func (f F) M() { fmt.Println(f) } func main() { var i I i = &T{"Hello"} describe(i) i.M() i = F(math.Pi) describe(i) i.M() } func describe(i I) { fmt.Printf("(%v, %T)\n", i, i) } //--- package main import "fmt" func main() { var i interface{} // empty interface describe(i) i = 42 describe(i) i = "hello" describe(i) } func describe(i interface{}) { fmt.Printf("(%v, %T)\n", i, i) } //--- // type switch package main import "fmt" func do(i interface{}) { switch v := i.(type) { case int: fmt.Printf("Twice %v is %v\n", v, v*2) case string: fmt.Printf("%q is %v bytes long\n", v, len(v)) default: fmt.Printf("I don't know about type %T!\n", v) } } func main() { do(21) do("hello") do(true) } //--- // format printout package main import "fmt" type IPAddr [4]byte // TODO: Add a "String() string" method to IPAddr. func (ip IPAddr) String() string { return fmt.Sprintf("%d.%d.%d.%d",ip[0],ip[1],ip[2],ip[3]) } func main() { hosts := map[string]IPAddr{ "loopback": {127, 0, 0, 1}, "googleDNS": {8, 8, 8, 8}, } for name, ip := range hosts { fmt.Printf("%v: %v\n", name, ip) } } //--- // error package main import ( "fmt" "math" ) type ErrNegativeSqrt float64 func (e ErrNegativeSqrt) Error() string { return fmt.Sprintf("cannot Sqrt negative number: %f",e) } func Sqrt(x float64) (float64, error) { if x < 0.0 { e:=ErrNegativeSqrt(x) return -1, &e } else { return math.Sqrt(x), nil } } func main() { fmt.Println(Sqrt(2)) fmt.Println(Sqrt(-2)) } //---- // reader emits infinite # of "A" package main import "golang.org/x/tour/reader" type MyReader struct{} func (r MyReader) Read(b []byte) (int, error) { b[0]='A' return 1, nil } // TODO: Add a Read([]byte) (int, error) method to MyReader. func main() { reader.Validate(MyReader{}) } //--- // a stream over another stream package main import ( "io" "os" "strings" ) type rot13Reader struct { r io.Reader } func (r rot13Reader) Read (b []byte) (int, error) { n,e := r.r.Read(b) for i:=0; i'm' { b[i]-=13 } else { b[i]=b[i]+13 } } return n, e } func main() { s := strings.NewReader("Lbh penpxrq gur pbqr!") r := rot13Reader{s} io.Copy(os.Stdout, &r) } //----- // image package main import ("golang.org/x/tour/pic" "image" "image/color" ) type Image struct{} func (im Image) ColorModel() color.Model { return color.RGBAModel } func (im Image) Bounds() image.Rectangle { return image.Rect(0,0,300,300) } func (im Image) At(x, y int) color.Color { return color.RGBA{uint8(x+y),uint8(x+y),255,255} } func main() { m := Image{} pic.ShowImage(m) } //--- package main import "fmt" func main() { ch := make(chan int, 2) // buffered channel ch <- 1 ch <- 2 fmt.Println(<-ch) fmt.Println(<-ch) } //--- // multiple channel package main import "fmt" func fibonacci(c, quit chan int) { x, y := 0, 1 for { select { case c <- x: x, y = y, x+y case <-quit: fmt.Println("quit") return } } } func main() { c := make(chan int) quit := make(chan int) go func() { for i := 0; i < 20; i++ { fmt.Println(<-c) } quit <- 0 }() fibonacci(c, quit) }