I'm pretty new to golang, and compiled languages in general, so please excuse my ignorance. In some code like this:
package main
import "fmt"
func assign() int {
return 1
}
func reference(foo *int) int {
*foo = 2
return 0
}
func main() {
var a, b int
a = assign()
reference(&b)
fmt.Println(a)
fmt.Println(b)
}
...what is the practical difference between assigning the value to a vs. passing b by reference?
In terms of real-world code, why does json.Unmarshal() require you to pass a pointer to your empty variable rather than just returning the Unmarshalled value so you can assign it to your variable?
Passing by value requires copying of parameters, however in case of reference, you just send the pointer to the object. Golang does pass by value by default, including for slices.
For the specific question about json.Unmarshal, I believe the reason is so that the Unmarshal code can verify whether the object passed in contains the same field names with compatible types as found in the json. For example, if json has a repeated field, there needs to be a corresponding slice in the object we are unmarshaling into.
So, we need to pass in the struct that we want the json string to unmarshal into. It needs to be a pointer so that Unmarshal can populate the fields. If you just pass a generic interface, Unmarshal will return a map. If Unmarshal did not take a pointer to a struct/interface, it could have been implemented to always return a map, but I think it is more useful this way.
This is a simple example, but might be useful - https://play.golang.org/p/-n8euepSS0