简体   繁体   中英

interface conversion: interface is map[string]interface {} not

I'm getting really confused by all the different types in Go, but I have a strictly defined struct 'VMR' and I'm trying to do a convert data to it.

I'm querying CouchDB (using the Go SDK) and then trying to assert the returned data into my struct. Of course this isn't working and it's throwing a panic. I'm shooting in the dark trying to figure out what I'm doing wrong.

Here is my function/struct:

type VMR struct {
    Name               string `json:"name,omitempty"`
    InUse              bool   `json:"inuse"`
    Description        string `json:"description,omitempty"`
    View               string `json:"view,omitempty"`
    Theme              string `json:"theme,omitempty"`
    Alias1             int    `json:"alias1,omitempty"`
    Alias1_Description string `json:"alias1_description,omitempty"`
    Host_PIN           int    `json:"host_pin,omitempty"`
    Allow_Guests       bool   `json:"allow_guests,omitempty"`
    Guest_Pin          int    `json:"guest_pin,omitempty"`
    Alias2             int    `json:"alias2,omitempty"`
    Alias2_Description string `json:"alias2_description,omitempty"`
}

func Get() VMR {
    cluster, _ := gocb.Connect("couchbase://ip:port")
    bucket, _ := cluster.OpenBucket("bucket", "password")
    myQuery := gocb.NewN1qlQuery("SELECT * FROM `bucket` WHERE name='test42' LIMIT 1")
    rows, _ := bucket.ExecuteN1qlQuery(myQuery, nil)

    var row interface{}
    rows.One(&row)
    fmt.Printf("Query1: %+v\n", row)

    return row.(VMR)
}

Full output:

Query1: map[115:map[alias1_description:Alias 1 description alias2_description:Alias description description:This is the best VMR name:test42 view:ViewOption theme:Theme51 alias1:1 alias2:1 guest_pin:1 host_pin:1 inuse:false]]

Error:

panic: interface conversion: interface is map[string]interface {}, not models.VMR

The viewResults.One(interface{}) call is a wrapper around Next(interface{}) which calls json.Unmarshal under the covers: Github link to relevant code . If you offer an interface{} object to Unmarshal , it will return to you a map[string]interface{} because it has no other option. Try this:

var row VMR
rows.One(&row)
fmt.Printf("Query1: %+v\n", row)

return row

...and that should handle the Unmarshal correctly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM