简体   繁体   中英

pointers in golang json unmarshalling

I'm trying to unmarshal a web service response using the below command and it works fine.

bodyBytes, _ := ioutil.ReadAll(response.Body)
bodyString := string(bodyBytes)
err = json.Unmarshal([]byte(bodyString), &output)
fmt.Println(&output)

When I use the pointer variable '&output' it works fine ie; the outputs are displayed properly.

but when I try to use the variable directly without &(ampersand), the outputs do not look good.

bodyBytes, _ := ioutil.ReadAll(response.Body)
bodyString := string(bodyBytes)
err = json.Unmarshal([]byte(bodyString), output)
fmt.Println(output)

What is the difference between these 2 variable - pointer vs normal variable while unmarshalling?

var output core.ApiData

The output is a type struct to match the apidata output.

As you can see, json.Unmarshal does not return a value, so if you passed a value instead of a pointer, it would have no way to work properly as it would fill its copy of the interface it takes as parameter.

The way it works is that you pass a pointer to the structure you want to fill, and json.Unmarshal will populate it directly using the pointer.

See the documentation for more details.

Unmarshal parses the JSON-encoded data and stores the result in the value pointed to by v . If v is nil or not a pointer, Unmarshal returns an InvalidUnmarshalError.

It is because the Unmarshal function takes the output struct and populates it with the data. If you do not pass a pointer, it will take a copy of your struct and fill it, after which you don't have access to it any more. If you pass a pointer, the output struct behind the pointer will be populated and remain available.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM