Understanding Go's Value Passing for Objects
In Go, function arguments are passed by value. When an object is passed as an argument, a copy of the object is created and passed to the function. This means that any changes made to the object within the function will not affect the original object outside the function.
Pointer Values in Go
However, it's important to understand the difference between passing a value and passing a pointer. A pointer is a reference to a memory location. When you pass a pointer to a function, you're passing the address of the object, not a copy of the object itself. This means that changes made to the object through the pointer will affect the original object outside the function.
To understand this concept, let's look at an example:
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") fmt.Printf("Address of s: %p\n", &s) for num := range s.queue { fmt.Printf("Value received: %d\n", num) s.number = num } done <- true } func main() { runtime.GOMAXPROCS(4) s := new(Something) fmt.Printf("Address of s in main: %p\n", &s) s.queue = make(chan int) done := make(chan bool) go gotest(s, done) // Passing a pointer to gotest s.queue <- 42 close(s.queue) <-done fmt.Printf("Address of s in main: %p\n", &s) fmt.Printf("Final value of s.number: %d\n", s.number) }
Output:
Address of s in main: 0x4930d4 from gotest: Address of s: 0x4974d8 Value received: 42 Address of s in main: 0x4930d4 Final value of s.number: 42
In this example:
Conclusion:
In Go, it's crucial to understand the difference between passing by value and passing by pointer. When you need to make changes to an object outside a function, pass a pointer to the object as an argument. However, for printing purposes, it's recommended to use the fmt package instead of using println(&s) to avoid any confusion regarding pointer values.
The above is the detailed content of How Does Go's Pass-by-Value Mechanism Affect Object Modification in Functions?. For more information, please follow other related articles on the PHP Chinese website!