This is a creation in Article, where the information may have evolved or changed.
Write a demo test, the channel is the transfer of data copies, or reference?
Expected: A reference type is passed
package mainimport ( "fmt")func main() { var sliceChan chan [2]map[string]int = make(chan [2]map[string]int, 2) //construct array m1 := map[string]int{ "rows":12, } m2 := map[string]int{ "columns":10, } bulk := [2]map[string]int{m1, m2} //directly read then sliceChan <- bulk e := <-sliceChan fmt.Println(e) //modify m2 m2["finish"] = 1 fmt.Println(e);}
The result of the final output is the same as expected. The printed result illustrates that E uses the address of the original data referenced.
[map[rows:12] map[columns:10]][map[rows:12] map[columns:10 finish:1]]
To modify the Chan data type, replace the following with an array, slice, and struct object.
Passing Array types
Just modify the Chan type, and the rest is unchanged. Modify the Chan type to [2]int type, others unchanged. Expected to return should be worth copying
func main() { var sliceChan chan [2]int = make(chan [2]int, 1) //construct array bulk := [2]int{1,2} //directly read then sliceChan <- bulk e := <-sliceChan fmt.Println(e) //modify m2 bulk[1] = 3 fmt.Println(e); fmt.Println(bulk)}
The return result is consistent with the expected:
[1 2][1 2][1 3]
Modify the type to slice
func main() { var sliceChan chan []int = make(chan []int, 1) //construct array bulk := []int{1,2} //directly read then sliceChan <- bulk e := <-sliceChan fmt.Println(e) //modify m2 bulk[1] = 3 fmt.Println(e); fmt.Println(bulk)}
Consistent with expectations, the pass-through is the same as the map, which is also quoted. The results returned are as follows:
[1 2][1 3][1 3]
Modify type to struct
It is expected that when a struct passes a value type, it is worth copying, passing the reference type, passing the reference
func main() { type people struct { name string age int } var sliceChan chan people = make(chan people, 1) //construct array bulk := people{ "zhangshan", 28, } //directly read then sliceChan <- bulk e := <-sliceChan fmt.Println(e) //modify m2 bulk.name = "wangwu" fmt.Println(e); fmt.Println(bulk)}
The above uses a value copy, and the result is exactly the same.
{zhangshan 28}{zhangshan 28}{wangwu 28}
When it is modified into a reference, it is indeed a reference passed.
Golang, why did you design this? What are the benefits of this design?