Go is an open source programming language that makes it easy to build simple, reliable, and efficient software. Go is a general purpose programming language with advanced features and a clean syntax. Because of its wide availability on a variety of platforms, its robust well-documented common library, and its focus on good software engineering principles, Go is an ideal language to learn as your first programming language. This is my learning note of GO Tour(https://tour.golang.org), just for reference and memory.
A closure is a function value that references variables from outside its body. The function may access and assign to the referenced variables; in this sense the function is “bound” to the variables.
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), ) } }
Flowcontrol
defer
A defer statement defers the execution of a function until the surrounding function returns. Deferred function calls are pushed onto a stack. When a function returns, its deferred calls are executed in last-in-first-out order.
func sum(a []int, c chan int) { sum := 0 for _, v := range a { sum += v } c <- sum // send sum to c }
func main() { a := []int{7, 2, 8, -9, 4, 0}
c := make(chan int) go sum(a[:len(a)/2], c) go sum(a[len(a)/2:], c) x, y := <-c, <-c // receive from c
fmt.Println(x, y, x+y) }
Buffered Channels
1
ch := make(chan int, 100)
Sends to a buffered channel block only when the buffer is full. Receives block when the buffer is empty.
Range and Close
A sender can close a channel to indicate that no more values will be sent. Receivers can test whether a channel has been closed by assigning a second parameter to the receive expression: after
1
v, ok := <-ch
ok is false if there are no more values to receive and the channel is closed.
The loop for i := range c receives values from the channel repeatedly until it is closed.