json - Go:指向接口(interface){} 的指针丢失底层类型

标签 json pointers reflection interface go

我正在使用 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/

相关文章:

c - 函数指针会使程序变慢吗?

c++ - 类型转换与 memcpy() : which one is better?

c - If 语句中使用的字符串指针不起作用

java - 使用其键和值(Javascript 或 jQuery)从嵌套 json 中删除对象

android - 在 android 中创建 JSON 对象失败

java - 循环访问对象数组并访问特定的键/值字段

json - 在Grails中渲染JSON

C# 反射 : Finding Attributes on a Member Field

java - 一个领域出错的反射(reflection)

c# - 反射和方法使用