Create a channel from an array
Create a channel from an array
What is the simplest way to add all the elements of an array to a channel?
I can do this:
elms := [3]int{1, 2, 3}
c := make(chan int, 3)
for _, e := range elms {
c <- e
}
But I wonder if there is a syntactic sugar for this.
Channels though aren't collections, even if they can be used like that. As the name implies, they are a channel of communication between processes/workers. The capacity specifies how many items can be queued before blocking. If the consumer is fast enough you won't need a large capacity even if you send a large array to the channel. The capacity is needed to prevent the producer from flooding the channel with unprocessed messages
– Panagiotis Kanavos
Jul 4 at 9:46
2 Answers
2
Code should be correct, maintainable, robust, reasonably efficient, and, most importantly, readable.
By design, Go is simple, but powerful. Everybody can read and memorize the specification: The Go Programming Language Specification. You can learn Go in a day or so. The simplicity makes Go code very readable.
The complexity of syntactic sugar induces cognitive overload. After working alongside Bjarne Stroustrup (C++) and Guido van Rossum (Python), the Go authors deliberately avoided syntactic sugar.
Read Bjarne Stroustrup's recent lament about the complexity of C++: Remember the Vasa!.
It's easy to see what this code does:
package main
func main() {
elms := [3]int{1, 2, 3}
c := make(chan int, len(elms))
for _, elm := range elms {
c <- elm
}
}
In Golang Spec on Channels It is defined as:-
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.
There is one more way to assign complete slice or array to the channel as:
func main() {
c := make(chan [3]int)
elms := [3]int{1, 2, 3}
go func() {
c <- elms
}()
for _, i := range <-c {
fmt.Println(i)
}
}
Check working example on Go Playground
For information on channels view this link https://dave.cheney.net/tag/golang-3
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
this is a valid question and not just for ease-of-use. When you know how many elements will be added you can pre-allocate buffers and avoid excessive garbage collection due to reallocations. The important information here though is the capacity, not the actual contents of the array. You already provided a capacity for your channel.
– Panagiotis Kanavos
Jul 4 at 9:41