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.
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 .
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With