Go – cannot use type interface {} as type person in assignment: need type assertion

go

I try to convert interface{} to struct person

package main

import (
    "encoding/json"
    "fmt"
)

func FromJson(jsonSrc string) interface{} {
    var obj interface{}
    json.Unmarshal([]byte(jsonSrc), &obj)

    return obj
}

func main() {

    type person struct {
        Name string
        Age  int
    }
    json := `{"Name": "James", "Age": 22}`

    actualInterface := FromJson(json)

    fmt.Println("actualInterface")
    fmt.Println(actualInterface)

    var actual person

    actual = actualInterface // error fires here -------------------------------

    // -------------- type assertion always gives me 'not ok'
    // actual, ok := actualInterface.(person)
    // if ok {

    //  fmt.Println("actual")
    //  fmt.Println(actual)
    // } else {
    //  fmt.Println("not ok")
    //  fmt.Println(actual)
    // }
}

… But got error:

cannot use type interface {} as type person in assignment: need type assertion

To solve this error I tried to use type assertion actual, ok := actualInterface.(person) but always got not ok.

Playground link

Best Answer

The usual way to handle this is to pass a pointer to the output value to your decoding helper function. This avoids type assertions in your application code.

package main

import (
    "encoding/json"
    "fmt"
)

func FromJson(jsonSrc string, v interface{}) error {
    return json.Unmarshal([]byte(jsonSrc), v)

}

func main() {
    type person struct {
        Name string
        Age  int
    }
    json := `{"Name": "James", "Age": 22}`

    var p person
    err := FromJson(json, &p)

    fmt.Println(err)
    fmt.Println(p)
}
Related Topic