繁体   English   中英

Go中的非指针错误,不确定是什么意思

[英]non-pointer error in Go not sure what it means

我有一个函数,它采用json解码器和接口作为论据,并且我正在解码为在接口上传递的结构。 像这样:

func DecodeJSON(decoder *json.Decoder, i interface{}) bool {
    if c, ok := i.(User); ok {
        err := decoder.Decode(c)
        if err != nil {
            fmt.Println(err)
            return false //err is not nil
        }
    }
    return false
}

功能用法:

// Register test
func HandleRequest(w rest.ResponseWriter, r *rest.Request) {

    decoder := json.NewDecoder(r.Body)
    user := User{}
    if DecodeJSON(decoder, user) {    
        fmt.Println("success")
}

我得到的错误:

json: Unmarshal(non-pointer main.User)

由于我的DecodeJSON没有使用user指针,因此此消息有点困惑。 所以不确定我的代码做错了什么。 希望有人可以解释,以便我能理解我的错误。

您需要使用指向用户的指针对数据进行解码,否则解码的数据将在对象的副本中解码,该对象的副本在函数返回时将被删除。

func DecodeJSON(decoder *json.Decoder, i interface{}) bool {
    if c, ok := i.(*User); ok {
        err := decoder.Decode(c)
        if err != nil {
            fmt.Println(err)
            return false //err is not nil
        }
    }
    return false
}

// Register test
func HandleRequest(w rest.ResponseWriter, r *rest.Request) {

    decoder := json.NewDecoder(r.Body)
    user := &User{}
    if DecodeJSON(decoder, user) {    
        fmt.Println("success")
}

保持接口参数不变,仅在传递用户和从接口获取用户时使用指针。

根据您的代码,最好将函数签名更改为func DecodeJSON(decoder *json.Decoder, user *User) bool

这将(1)消除显式的运行时强制转换,并且(2)减少代码的歧义性,安全性和编译时检查。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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