我有一个像这样的小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
的另一个名称。