golang 推荐通过消息来共享内存,而不是通过共享内存来通信
chanel 是一等公民可以作为函数参数,函数返回值
chanel 必须有接受者,否则会deadlock
func worker(id int, c chan int) {
fmt.Println(123)
// for n := range c {
// fmt.Printf("Worker %d received %c\n",
// id, n)
// }
}
func chanDemo() {
channel := make(chan int,3)
go worker(0, channel)
channel <- 'a' + 0
channel <- 'a' + 1
channel <- 'a' + 2
channel <- 'a' + 3
time.Sleep(time.Millisecond)
}
func main() {
chanDemo()
}
函数时一等公民可以作为函数参数和返回参数
func adder() func(int) int {
sum := 0
return func(v int) int {
sum += v
return sum
}
}
type iAdder func(int) (int, iAdder)
func adder2(base int) iAdder {
return func(v int) (int, iAdder) {
return base + v, adder2(base + v)
}
}
func main() {
// a := adder() is trivial and also works.
a := adder2(0)
for i := 0; i < 10; i++ {
var s int
s, a = a(i)
fmt.Printf("0 + 1 + ... + %d = %d\n",
i, s)
}
}
有疑问加站长微信联系(非本文作者)