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

接口如何表示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?

图片转代码服务由CSDN问答提供 功能建议

据说 interface {} 表示Go中的任何类型。 例如,让我们考虑 encoding / json 中的 Marshal 函数,该函数用于将Go数据结构转换为JSON字符串。 它的定义是

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

我们将一个结构作为参数传递给它,如下所示。

 类型hello struct {
消息字符串
} 
data,err:= json.Marshal(hello {消息:'Hello world'})
   
 
 

Go如何处理此问题?

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

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.

    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题