我正在使用 Go 中的一些“通用”函数,这些函数在 interface{}
上运行并在 channel 周围发送东西,等等。精简一下,假设我有类似的东西:
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
的调用看到了一个类型为 pointer-to-interface 而不是 pointer-to-MyType 的值。
为什么我在使用 &v
时会丢失类型信息?我希望输出的第二行是 *MyType
而不是 *interface {}
。
有什么方法可以在不显式转换的情况下调用自定义 JSON Marshaller?
最佳答案
只需将指针传递给您的结构,而不是将其值传递给函数。指针仍然是 interface{}
但指向接口(interface)的指针没有意义。
关于json - Go:指向接口(interface){} 的指针丢失底层类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26960243/