Home >Backend Development >Golang >Are Go Channels Passed by Reference or Value?
Are Channels Implicitly Passed by Reference?
The Go tour provides an example of channels that raises questions about their passing mechanism. By passing a channel into the sum function, the changes made to it within the function persist, leaving open the possibility of implicit reference passing.
Explanation
Technically, channels are copied when passed because make creates heap-allocated memory that effectively acts as a pointer. However, this pointer is not exposed, allowing channels to be treated as reference types.
The specification clarifies that the built-in make function returns a value of type T (not *T) and initializes the memory. When used with channels, make initializes the channel and makes it usable as a reference type.
Implications
This behavior means that when you pass channels created with make into functions, you can read and write to them without copying the underlying data.
Reference Types vs Value Types
The following types are passed by reference in Go:
Data types like numbers, bools, and structs are copied when passed into functions.
The above is the detailed content of Are Go Channels Passed by Reference or Value?. For more information, please follow other related articles on the PHP Chinese website!