[英]non-pointer error in Go not sure what it means
I have a function that takes a json decoder and an interface as its arguements, and i am decoding to a struct that is passed on the interface. 我有一个函数,它采用json解码器和接口作为论据,并且我正在解码为在接口上传递的结构。 Like so:
像这样:
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
}
Usage of the function: 功能用法:
// Register test
func HandleRequest(w rest.ResponseWriter, r *rest.Request) {
decoder := json.NewDecoder(r.Body)
user := User{}
if DecodeJSON(decoder, user) {
fmt.Println("success")
}
Error i am getting: 我得到的错误:
json: Unmarshal(non-pointer main.User)
Bit confused by this message since my DecodeJSON is not taking a pointer for user
. 由于我的DecodeJSON没有使用
user
指针,因此此消息有点困惑。 So am not sure what i have done wrong with my code. 所以不确定我的代码做错了什么。 Hope some one can explain so i can understand my mistake.
希望有人可以解释,以便我能理解我的错误。
You need to use a pointer to a user to decode the data in, otherwise the decoded data gets decoded in a copy of the object that gets deleted when the function returns. 您需要使用指向用户的指针对数据进行解码,否则解码的数据将在对象的副本中解码,该对象的副本在函数返回时将被删除。
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")
}
Leave the interface parameter as is, just use a pointer when you pass the User and when you get the user from the interface. 保持接口参数不变,仅在传递用户和从接口获取用户时使用指针。
Based on your code, you'd better change your function signature to func DecodeJSON(decoder *json.Decoder, user *User) bool
根据您的代码,最好将函数签名更改为
func DecodeJSON(decoder *json.Decoder, user *User) bool
This will (1) eliminate explicit runtime cast, and (2) make your code less ambiguous and safe and compile-time checked. 这将(1)消除显式的运行时强制转换,并且(2)减少代码的歧义性,安全性和编译时检查。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.