dongyan0629 2018-08-04 08:16
浏览 121
已采纳

接口如何表示Golang中的任何类型

It is said that interface{} represents any type in Go. For example, let us consider a Marshal function in encoding/json which is used to convert Go data structure into a JSON string. Its definition is

func Marshal(v interface{}) ([]byte, error) 

But we are passing a struct to it as a parameter like below.

type hello struct{
   Message string
}
data,err:= json.Marshal(hello{Message:'Hello world'})

How is Go handling this?

  • 写回答

1条回答 默认 最新

  • dongpo1599 2018-08-04 08:55
    关注

    The answer is runtime reflection.

    From docs:

    Package reflect implements run-time reflection, allowing a program to manipulate objects with arbitrary types. The typical use is to take a value with static type interface{} and extract its dynamic type information by calling TypeOf, which returns a Type.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 有没有帮写代码做实验仿真的
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥30 vmware exsi重置后登不上
  • ¥15 易盾点选的cb参数怎么解啊
  • ¥15 MATLAB运行显示错误,如何解决?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?