In the provided code snippet, a channel c is created using the make() function and passed to the sum function. The question arises: are channels implicitly passed by reference in Go, even though no explicit pointer is created?
The answer lies in the unique behavior of make(). Technically, channels are copied, as make() allocates memory on the heap, creating a pointer behind the scenes. However, this pointer type is not exposed, resembling a reference type.
According to the Go specification:
"The built-in function make takes a type T, which must be a slice, map or channel type, optionally followed by a type-specific list of expressions. It returns a value of type T (not *T)."
By using make(), the channel is initialized, allowing it to be employed as a reference type. Hence, it can be passed without replicating the underlying data.
In summary, channels are effectively passed by reference in Go when created using make. This applies to other data structures such as slices, maps, pointers, and functions. On the other hand, primitive data types (numbers, bools) and mutable structs are copied when passed to functions.
The above is the detailed content of Are Channels Passed by Reference in Go?. For more information, please follow other related articles on the PHP Chinese website!