nicht verwenden, geben Sie interface {} als Typ person bei Belegung: brauchen Typ-assertion

Ich versuche zu konvertieren interface{} zu 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)
    //}
}

... Aber bekam die Fehlermeldung:

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

Lösen diesen Fehler habe ich versucht zu verwenden, geben Sie die Geltendmachung actual, ok := actualInterface.(person) kam aber immer not ok.

Spielplatz link

Schreibe einen Kommentar