pointers - What's the difference between variable assignment and passing by reference? -
i'm pretty new golang, , compiled languages in general, please excuse ignorance. in code 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 = assign() reference(&b) fmt.println(a) fmt.println(b) }
...what practical difference between assigning value vs. passing b reference?
in terms of real-world code, why json.unmarshal() require pass pointer empty variable rather returning unmarshalled value can assign variable?
passing value requires copying of parameters, in case of reference, send pointer object. golang pass value default, including slices.
for specific question json.unmarshal, believe reason unmarshal code can verify whether object passed in contains same field names compatible types found in json. example, if json has repeated field, there needs corresponding slice in object unmarshaling into.
so, need pass in struct want json string unmarshal into. needs pointer unmarshal can populate fields. if pass generic interface, unmarshal return map. if unmarshal did not take pointer struct/interface, have been implemented return map, think more useful way.
this simple example, might useful - https://play.golang.org/p/-n8euepss0
Comments
Post a Comment