Unmarshalling JSON in golang

I am trying to understand the difference between interface{} and &interface{}. I am getting confused why for first code snippet unmarshalling is done in a Map datatype and in second snippet unmarshalling is done in struct datatype.

case : 1

package main

import (
	"encoding/json"
	"fmt"
)

type Person struct {
	Name string `json:"name"`
}

func Decode(p interface{}) {
	str := `
        {"name" : "aryan"}
    `
	json.Unmarshal([]byte(str), &p)
	fmt.Printf("%+v \n", p)
}

func main() {
	p := Person{}
	Decode(p)
	fmt.Printf("%+v \n", p)
}

Output

map[name:aryan] 
{Name:} 

case : 2

package main

import (
	"encoding/json"
	"fmt"
)

type Person struct {
	Name string `json:"name"`
}

func Decode(p interface{}) {
	str := `
        {"name" : "aryan"}
    `
	json.Unmarshal([]byte(str), &p)
	fmt.Printf("%+v \n", p)
}

func main() {
	p := &Person{}
	Decode(p)
	fmt.Printf("%+v \n", p)
}

Output

&{Name:aryan} 
&{Name:aryan} 

I am clear with case 1, 3, and 4. But here in case 2 we are passing address in interface value and then address of that pointer is passed again in unmarshalling. So how unmarshalling is working with pointer to pointer ?

case : 3

package main

import (
	"encoding/json"
	"fmt"
)

type Person struct {
	Name string `json:"name"`
}

func Decode(p interface{}) {
	str := `
        {"name" : "aryan"}
    `
	json.Unmarshal([]byte(str), p)
	fmt.Printf("%+v \n", p)
}

func main() {
	p := &Person{}
	Decode(p)
	fmt.Printf("%+v \n", p)
}

Output

&{Name:aryan} 
&{Name:aryan} 

case : 4

package main

import (
	"encoding/json"
	"fmt"
)

type Person struct {
	Name string `json:"name"`
}

func Decode(p interface{}) {
	str := `
        {"name" : "aryan"}
    `
	json.Unmarshal([]byte(str), p)
	fmt.Printf("%+v \n", p)
}

func main() {
	p := Person{}
	Decode(p)
	fmt.Printf("%+v \n", p)
}

Output

{Name:} 
{Name:}  

Hi @aryanmaurya1,

Function Decode() has an interface type as parameter, but the actual argument p in the call to Decode(p) is a pointer to Person.

You can confirm this by printing out the Type of p inside Decode():

	json.Unmarshal([]byte(str), &p)
	fmt.Printf("%T \n", p)  // T for "type"

Output:

*main.Person 

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