将切片的所有项添加到通道中。

huangapple go评论69阅读模式
英文:

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{&quot;lol&quot;, &quot;cat&quot;, &quot;lolcat&quot;}

go func() {
    for _, v := range values {
        ch &lt;- v
    }
}()

I was looking for something like ch &lt;- 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 &lt;- 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) &lt;-chan T {
    ch := make(chan T, len(s))
    for _, e := range s {
        ch &lt;- e
    }
    close(ch)
    return ch
}

https://go.dev/play/p/c5v4df_M1IG

答案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 &quot;fmt&quot;

func main() {
	ch := make(chan []string)
	values := []string{&quot;lol&quot;, &quot;cat&quot;, &quot;lolcat&quot;}

	go func() {
			ch &lt;- values
	}()
	
	fmt.Printf(&quot;Values : %+v\n&quot;, &lt;-ch)
}

huangapple
  • 本文由 发表于 2015年10月6日 20:40:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/32970224.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定