学习实例(二)—— goroutine 和 channel
前一章:欢迎访问 Go语言学习(一)
Linux 下编写方法:
1 |
vim sum_by_group.go |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
package main import "fmt" func sum(a []int, result chan int) { sum := 0 for _, v := range a { sum += v } result <- sum } func main() { a := []int{2, 3, 5, 6, 10, -5, 1, 0} result := make(chan int) go sum(a[:len(a)/2], result) go sum(a[len(a)/2:], result) x, y := <-result, <-result fmt.Println(x, y, x+y) } |
以上是[……]