Go: cmd/vet: reject json.Unmarshal(data, non-pointer)

Created on 8 Sep 2018  路  4Comments  路  Source: golang/go

Here is a snippet from encoding/json

func Unmarshal(data []byte, v interface{}) error 

In that snippet v is an interface{} . So it can be anything. But it needs to be a pointer to receive the unmarshaled value.

If we don't use a pointer we will get a runtime error. And it's must be a pointer.

Can we add a build tag to throw error when a interface is not a pointer?

So that, we can get a compile time error if that interface must be a pointer instead of runtime error.

FrozenDueToAge NeedsFix Proposal Proposal-Accepted help wanted

Most helpful comment

The way to reject this code early would be with cmd/vet. This would apply to gob and xml too, of course: you can't unmarshal into a non-(pointer or interface).

All 4 comments

The way to reject this code early would be with cmd/vet. This would apply to gob and xml too, of course: you can't unmarshal into a non-(pointer or interface).

I've made a start on implementing this check.

Change https://golang.org/cl/139997 mentions this issue: cmd/vet: detect non-pointer arguments for unmarshal and decode

Change https://golang.org/cl/148562 mentions this issue: go/analysis/passes/unmarshal: port vet's unmarshal checker

Was this page helpful?
0 / 5 - 0 ratings