从数组创建通道

Create a channel from an array

将数组的所有元素添加到通道的最简单方法是什么?

我能做到:

elms := [3]int{1, 2, 3}
c := make(chan int, 3)

for _, e := range elms {
    c <- e
}

但我想知道是否有语法糖。

Golang Spec on Channels中定义为:-

A single channel may be used in send statements, receive operations, and calls to the built-in functions cap and len by any number of goroutines without further synchronization.

还有一种方法可以将完整的切片或数组分配给通道:

func main() {
    c := make(chan [3]int)

    elms := [3]int{1, 2, 3}

    go func() {
        c <- elms
    }()

    for _, i := range <-c {
        fmt.Println(i)
    }
}

检查 Go Playground

上的工作示例

有关频道的信息,请查看此 link https://dave.cheney.net/tag/golang-3

代码应该是正确的、可维护的、健壮的、相当高效的,最重要的是,可读。

根据设计,Go 很简单,但功能强大。每个人都可以阅读并记住规范:The Go Programming Language Specification。您可以在一天左右的时间内学会围棋。简单性使得 Go 代码非常可读。

语法糖的复杂性导致认知超载。在与 Bjarne Stroustrup (C++) and Guido van Rossum (Python) 一起工作后,Go 作者故意避免了语法糖。

阅读 Bjarne Stroustrup 最近对 C++ 的复杂性的哀叹:Remember the Vasa!

很容易看出这段代码的作用:

package main

func main() {
    elms := [3]int{1, 2, 3}
    c := make(chan int, len(elms))
    for _, elm := range elms {
        c <- elm
    }
}