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:}