In Go, function arguments are passed by value, meaning that any changes made to the arguments within the function do not affect the original values outside the function. This can be confusing when dealing with structs, as you may expect them to be passed by reference.
To understand how this works, consider the following code snippet:
package main import ( "fmt" "runtime" ) type Something struct { number int queue chan int } func gotest(s *Something, done chan bool) { fmt.Printf("from gotest:\n&s: %p\n", &s) for num := range s.queue { fmt.Println(num) s.number = num } done <- true } func main() { runtime.GOMAXPROCS(4) s := &Something{number: 42} fmt.Printf("&s: %p\n", &s) s.queue = make(chan int) done := make(chan bool) go gotest(s, done) s.queue <- 43 close(s.queue) <-done fmt.Printf("&s: %p\n", &s) fmt.Println(s.number) // Output: 43 }
This code demonstrates passing a struct pointer by value. In the main function, we create an instance of Something and pass a pointer to it to the gotest function.
Within the gotest function, we modify the number field of the struct and also pass messages to its queue channel. The gotest function operates on a copy of the pointer, so any changes it makes will not affect the original struct in the main function.
Using the &s expression, we can observe the pointer values at various stages of execution. The output shows that:
This behavior is consistent with Go's pass-by-value semantics, where arguments are copied into the function's scope. Hence, if you want to modify the original struct, you should pass a pointer to it rather than the struct itself.
The above is the detailed content of How Do Go's Pass-by-Value Semantics Affect Struct Pointer Manipulation?. For more information, please follow other related articles on the PHP Chinese website!