Home >Backend Development >Golang >Are Channels Passed by Value or Reference in Go?
Are Channels Passed by Reference by Default?
In Go, the built-in function make creates instances of slices, maps, and channels. These types are not directly passed by reference, but technically behave as such due to the allocation of memory on the heap during their initialization.
The following channel example demonstrates this behavior:
package main import "fmt" func sum(a []int, c chan int) { sum := 0 for _, v := range a { sum += v } c <- sum } func main() { a := []int{7, 2, 8, -9, 4, 0} c := make(chan int) go sum(a[:len(a)/2], c) go sum(a[len(a)/2:], c) x, y := <-c, <-c fmt.Println(x, y, x+y) }
In this example, the channel c is initialized using make, creating a reference-like behavior. Any changes made to c within the sum function persist after the function terminates.
This behavior is further explained in 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). The memory is initialized as described in the section on initial values.
因此,切片、映射和通道可以被视为引用类型,尽管它们在技术上是按值传递的。这使得它们可以传递给函数并允许写入或读取,类似于指针的行为。
The above is the detailed content of Are Channels Passed by Value or Reference in Go?. For more information, please follow other related articles on the PHP Chinese website!