Passing empty interface changes type

Hi everyone

I’m writing some code to test unmarshalling jsons. To avoid to write a lot of code i wrote a function that you can pass the json, a holder to be passed as pointer to the Go’s unmarshal method and a struct that i expect

So instead of writing a lot of tests with this syntax

Code that works:

	var holderNull1 int32Holder
	jsonNull1 := "{}"
	if err := json.Unmarshal([]byte(jsonNull1), &holderNull1); err != nil {
		t.Error("Unexpected error ", err)
	}
	assertEq(holderNull1,int32Holder{Holder: NewInt32OptEmpty()}, t)

I wrote this helper function

func testUnmarshal(jsonValue string, holder interface{}, expect interface{}, t *testing.T) {
	if err := json.Unmarshal([]byte(jsonValue), &holder); err != nil {
		t.Error("Unexpected error ", err)
	}
	println(holder)
	assertEq(holder,expect, t)
}

and call it with

testUnmarshal("{}", int32Holder{}, int32Holder{Holder: NewInt32OptEmpty()}, t)

The second approach says, that holder passed is of type map[string]interface {} so passing a struct to a function and then pass it as a pointer seems to change it’s type.

What am I missing?

I’ve put together a small example on go playground:

https://play.golang.org/p/WYOyhrNEDS5

What’s the type definition of int2Holder? Is thr code available somewhere that we could try running it to reproduce it? If not, can you make a small reproducible scenario?

I’ve put together a small example on go playground:

https://play.golang.org/p/WYOyhrNEDS5

Updated the code by passing the address. below is the working one

https://play.golang.org/p/crbUdJG-E96

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.