1 回答

TA贡献1895条经验 获得超3个赞
空接口不是实际类型,它基本上是匹配任何内容的东西。正如评论中所述,指向空接口的指针实际上没有意义,因为指针已经与空接口匹配,因为所有内容都与空接口匹配。为了让你的代码正常工作,你应该删除结构周围的接口包装器,因为这只会扰乱 json 类型检查,而空接口的全部意义在于你可以向它传递任何内容。
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"log"
)
type myStruct struct {
A string `json:"a"`
B string `json:"b"`
}
func main() {
jsonBlob := []byte(`{"a":"test","b":"test2"}`)
var foo = &myStruct{} // This need to be a pointer so its attributes can be assigned
closer := ioutil.NopCloser(bytes.NewReader(jsonBlob))
err := unmarshalCloser(closer, foo)
if err != nil {
log.Fatal(err)
}
fmt.Println(fmt.Sprintf("%v", foo))
// That´s what i want:
fmt.Println(foo.A)
}
// You don't need to declare either of these arguments as pointers since they're both interfaces
func unmarshalCloser(closer io.ReadCloser, v interface{}) error {
defer closer.Close()
// v NEEDS to be a pointer or the json stuff will barf
// Simplified with the decoder
return json.NewDecoder(closer).Decode(v)
}
- 1 回答
- 0 关注
- 143 浏览
添加回答
举报