go语言的range循环可以直接在channels上面迭代。使用range循环一次从channel中接受数据,当channel被关闭并且没有值可接受时跳出循坏。
func main() {
natures := make(chan int)
squares := make(chan int)
go func() {
for x := 0; x < 100; x++ {
natures <- x
}
close(natures)
}()
go func() {
for x := range natures {
squares <- x * x
}
close(squares)
}()
for x := range squares {
(x)
}
}
双向channel可以隐式转换为单向channel,反之不行
func main() {
natures := make(chan int)
squares := make(chan int)
go counter(natures)
go squar(natures,squares)
printer(squares)
}
func squar(in <-chan int,out chan<- int) {
for i:= range in {
out <- i*i
}
close(out)
}
func printer(in <-chan int) {
for i := range in {
(i)
}
}
func counter(out chan<- int) {
for i:=0;i<100;i++ {
out <- i
}
close(out)
}
多个goroutines并发地向同一个channel发送数据,返回最快响应的,此时应该采用有缓冲的channel,否则,其他goroutine返回之后没有通道接受,则产生goroutine卡死,泄露
func mirroredQuery() string {
responses := make(chan string, 3)
go func() { responses <- request("") }()
go func() { responses <- request("") }()
go func() { responses <- request("") }()
return <-responses // return the quickest response
}