Golang interface {} causes misunderstanding

I have an error in Go when using a parameter type interface{}as a function, when a non-pointer type is given, and using json.Unmarshalit.

Since a piece of code is worth a thousand words, here is an example:

package main

import (
    "encoding/json"
    "fmt"
)

func test(i interface{}) {
    j := []byte(`{ "foo": "bar" }`)
    fmt.Printf("%T\n", i)
    fmt.Printf("%T\n", &i)
    json.Unmarshal(j, &i)
    fmt.Printf("%T\n", i)
}

type Test struct {
    Foo string
}

func main() {
    test(Test{})
}

What outputs:

main.Test
*interface {}
map[string]interface {}

json.Unmarshalturns my structure into map[string]interface{}oO ...

Short readings later explain some of them interface{}- this is a type in itself, and not some kind of unconventional container that explains *interface{}, and the fact that json.Unmarshalit could not get the initial type and returned a map[string]interface{}..

From Unmarshaldocs:

To unmount JSON into an interface value, Unmarshal saves one of them in an interface value: [...]

And if I pass a pointer to a test function like this, it works:

func test(i interface{}) {
    j := []byte(`{ "foo": "bar" }`)
    fmt.Printf("%T\n", i)
    fmt.Printf("%T\n", &i)
    json.Unmarshal(j, i)
    fmt.Printf("%T\n", i)
    fmt.Println(i)
}

func main() {
    test(&Test{})
}

What outputs:

*main.Test
*interface {}
*main.Test
&{bar}

, , & Unmarshal. *Test i, .

, , & i Unmarshal, i. .

:

func test(i interface{}) {
    j := []byte(`{ "foo": "bar" }`)
    fmt.Printf("%T\n", i)
    fmt.Printf("%T\n", &i)
    json.Unmarshal(j, &i)
    fmt.Printf("%T\n", i)
    fmt.Println(i)
}

func main() {
    test(&Test{})
}

, :

*main.Test
*interface {}
*main.Test
&{bar}

Google.

+4
1

interface{} - . (value; type), . : # .

json.Unmarshal() interface{}:

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

, interface{} (i interface{} test() ), , .

, , interface{}, . , i . , *Test test(), test() i json.Unmarshal() ( ).

i *Test &i, , json *interface{} , interface{} , *Test . , : unmarshals JSON Test.

i Test &i, , : *interface{} , interface{}, -: Test. json , , . json.Unmarshal() *interface{}, json interface{}. , json , . json JSON map[string]interface{} , , ( , : &i).

, . "" ( ). interface{}, , .

+4

Source: https://habr.com/ru/post/1650549/


All Articles