转到json.解组不适用于json的类型定义.RawMessage



我有一个像这样的小Go程序:

package main
import "encoding/json"
func main() {
bs := []byte(`{"items": ["foo", "bar"]}`)
data := Data{}
err := json.Unmarshal(bs, &data)
if err != nil {
panic(err)
}
}
type Data struct {
Items []Raw `json:"items"`
}
// If I do this, this program panics with "illegal base64 data at input byte 0"
type Raw json.RawMessage
// This works
type Raw = json.RawMessage

为什么json.Unmarshal使用类型别名而不使用类型定义?这个错误信息是什么意思?

这是一个新的类型定义:

type Raw json.RawMessage

Raw类型是从json.RawMessage派生而来的,但它是一个没有为json.RawMessage定义任何方法的新类型。因此,如果json.RawMessage有json解组器方法,那么Raw就没有。以下代码不会将Raw类型的变量t识别为json.RawMessage:

if t, ok:=item.(json.RawMessage); ok {
...
}

这是一个类型别名:

type Raw = json.RawMessage

这里,Raw具有json.RawMessage所具有的所有方法,并且对json.RawMessage的类型断言将起作用,因为Raw只是json.RawMessage的另一个名称。

最新更新