这是代码:
import "fmt"
func main() {
messages := make(chan string, 1)
go func(c chan string) {
c <- "Hi"
}(messages)
select {
case msg := <-messages:
fmt.Println("received message", msg)
default:
fmt.Println("no message received")
}
}
它输出no message received. 或者这段代码:
import (
"fmt"
"time"
)
func f(from string) {
for i := 0; i < 3; i++ {
fmt.Println(from, ":", i)
}
}
func main() {
go f("goroutine")
go func(msg string) {
fmt.Println(msg)
}("going")
time.Sleep(time.Second)
fmt.Println("done")
}
意外打印
going
goroutine : 0
goroutine : 1
goroutine : 2
尽管 goroutine 的going调用晚于计数器。为什么?
陪伴而非守候
相关分类