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 關注
- 169 瀏覽
添加回答
舉報