← 返回主页

第9课: 通道 (Channels)

创建通道

ch := make(chan int)
buffered := make(chan string, 10)

发送和接收

ch <- 42      // 发送
value := <-ch // 接收

// 关闭通道
close(ch)

通道示例

func sum(nums []int, ch chan int) {
    total := 0
    for _, n := range nums {
        total += n
    }
    ch <- total
}

func main() {
    nums := []int{1, 2, 3, 4, 5, 6}
    ch := make(chan int)

    go sum(nums[:3], ch)
    go sum(nums[3:], ch)

    x, y := <-ch, <-ch
    fmt.Println(x + y)
}

select 语句

select {
case msg := <-ch1:
    fmt.Println("收到:", msg)
case ch2 <- value:
    fmt.Println("发送成功")
case <-time.After(time.Second):
    fmt.Println("超时")
default:
    fmt.Println("无操作")
}

range 遍历通道

ch := make(chan int, 5)
for i := 0; i < 5; i++ {
    ch <- i
}
close(ch)

for value := range ch {
    fmt.Println(value)
}