I'm writing some code where a number of functions update items that are "passed by reference", along the lines of DoSomethingB# below ## lines. As a newbie, this is rather unintuitive to me. I'd rather have a function return its result (unless it might be a method and update the receiver).
By
DoSomethingA?
(not a structure method)
Is this considered good or acceptable style in Go?
package main import ( "fmt" ) func DoSomethingA(someData int) int { return someData + 23 } func DoSomethingB(someData *int) { *someData = *someData + 23 } func DoSomethingC(someData *int) *int { tmp := *someData + 23 return &tmp } func main() { someDataA := 19 someDataB := 19 someDataC := 19 fmt.Printf("1) someDataA=%d, someDataB=%d, someDataC=%d\n", someDataA, someDataB, someDataC) someDataA = DoSomethingA(someDataA) DoSomethingB(&someDataB) someDataC = *DoSomethingC(&someDataC) fmt.Printf("2) someDataA=%d, someDataB=%d, someDataC=%d\n", someDataA, someDataB, someDataC) }
DoSomethingB vs. DoSomethingA: If you want to modify the original variable without creating a copy, it is helpful to use a pattern like DoSomethingB, thus avoiding unnecessary allocations . However, it may make the code harder to understand. Using
DoSomethingA (which returns a result) is generally more idiomatic in Go and is often preferred for readability reasons.
Is DoSomethingB considered good style in Go? : While it's not uncommon to see code like DoSomethingB in Go, especially when dealing with large data structures, Go's idiomatic approach encourages return values to modify pointers. Using pointers to modify values directly (especially for built-in types such as integers) can lead to code that is difficult to understand.
DoSomethingC would be considered ungrammatical because it returns a pointer to a local variable. This may lead to undefined behavior because the memory location may be reused for other purposes after the function returns. It's best to avoid this pattern.
DoSomethingA. If you have a good reason to modify the original data and are worried about performance (such as large data structures), then
DoSomethingB is acceptable.
The above is the detailed content of When does Go return a value, return a reference, or return nothing?. For more information, please follow other related articles on the PHP Chinese website!