Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add all the items of a slice into a channel

Tags:

slice

go

channel

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.

like image 552
dotvav Avatar asked Oct 06 '15 12:10

dotvav


People also ask

How do I add items to my slice?

To add an element to a slice , you can use Golang's built-in append method. append adds elements from the end of the slice. The first parameter to the append method is a slice of type T . Any additional parameters are taken as the values to add to the given slice .

How to append multiple slices in Golang?

Slice concatenation in Go is easily achieved by leveraging the built-in append() function. It takes a slice ( s1 ) as its first argument, and all the elements from a second slice ( s2 ) as its second.

How to concatenate slices in Golang?

When it comes to appending a slice to another slice, we need to use the variadic function signature dots. In variadic functions in Golang, we can pass a variable number of arguments to the function and all the numbers can be accessed with the help of the argument name.


1 Answers

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.

like image 190
PerryJones Avatar answered Oct 06 '22 06:10

PerryJones