英文:
Add all the items of a slice into a channel
问题
在Go语言中,是否有一种更符合惯用方式的方法将数组/切片的所有元素添加到通道中,而不是像下面这样做?
ch := make(chan string)
values := []string{"lol", "cat", "lolcat"}
go func() {
    for _, v := range values {
        ch <- v
    }
}()
我希望能够像 ch <- values... 这样做,但是编译器会拒绝这种写法。
英文:
In Go, is there a more idiomatic way to add all of the elements of an array/slice into a channel than the following?
ch := make(chan string)
values := []string{"lol", "cat", "lolcat"}
go func() {
    for _, v := range values {
        ch <- v
    }
}()
I was looking for something like ch <- values... but that is rejected by the compiler.
答案1
得分: 1
一个for/range循环是将切片的所有元素发送到通道的惯用方法:
for _, v := range values {
    ch <- v
}
不必像问题中所示在goroutine中运行for循环。
英文:
A for/range loop is the idiomatic way to send all of the elements of a slice to a channel:
for _, v := range values {
    ch <- v
}
It is not necessary to run the for loop in a goroutine, as shown in the question.
答案2
得分: 1
直到迭代器出现之前,是的,你写的代码是最符合惯用写法的。我将其封装为可在我工作的代码库中重用的形式,类似于以下代码:
// ToChan 返回一个包含切片 s 中所有元素的通道。
// 当所有元素都从通道中消费完毕时,通道将被关闭。
func ToChan[T any](s []T) <-chan T {
    ch := make(chan T, len(s))
    for _, e := range s {
        ch <- e
    }
    close(ch)
    return ch
}
https://go.dev/play/p/c5v4df_M1IG
英文:
Until iterators will come along, yes, the code you wrote is as idiomatic as it gets. I have it packaged for reuse as something like this in codebases I work on:
// ToChan returns a channel containing all elements in the slice s.
// The channel is closed when all elements are consumed from the channel.
func ToChan[T any](s []T) <-chan T {
    ch := make(chan T, len(s))
    for _, e := range s {
        ch <- e
    }
    close(ch)
    return ch
}
答案3
得分: -1
你可以声明一个字符串数组的通道,除非你绝对想要保留一个字符串的通道:
package main
import "fmt"
func main() {
    ch := make(chan []string)
    values := []string{"lol", "cat", "lolcat"}
    go func() {
        ch <- values
    }()
    fmt.Printf("Values: %+v\n", <-ch)
}
这段代码创建了一个通道 ch,类型为字符串数组。然后,将字符串数组 values 发送到通道 ch 中,并通过 <-ch 接收通道中的值,并使用 fmt.Printf 打印出来。
英文:
You can declare a chan of string arrays, unless you absolutely want to keep a chan of strings :
package main
import "fmt"
func main() {
	ch := make(chan []string)
	values := []string{"lol", "cat", "lolcat"}
	go func() {
			ch <- values
	}()
	
	fmt.Printf("Values : %+v\n", <-ch)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论