【发布时间】:2015-01-13 15:07:27
【问题描述】:
我正在使用 Go 中的一些“通用”函数,这些函数在 interface{} 上运行并通过通道等发送内容。精简,假设我有类似的东西:
type MyType struct {
// Fields
}
func (m *MyType) MarshalJSON() ([]byte, error) {
// MarshalJSON
log.Print("custom JSON marshal")
return []byte("hello"), nil
}
func GenericFunc(v interface{}) {
// Do things...
log.Print(reflect.TypeOf(v))
log.Print(reflect.TypeOf(&v))
b, _ = json.Marshal(&v)
fmt.Println(string(b))
}
func main() {
m := MyType{}
GenericFunc(m)
}
这个输出:
2014/11/16 12:41:44 MyType
2014/11/16 12:41:44 *interface {}
后跟默认json.Marshal 输出,而不是自定义输出。据我所知,这是因为对Marshal 的调用看到的是指向接口而不是指向MyType 的指针类型的值。
为什么我在输入&v 时会丢失类型信息?我希望输出的第二行是*MyType 而不是*interface {}。
我有什么方法可以在不显式转换的情况下调用自定义 JSON Marshaller?
【问题讨论】:
标签: json pointers reflection interface go