[英]Difference between map[string]interface{} and interface{}
I want to parse a JSON file to a map[string]interface{}
: 我想将JSON文件解析为
map[string]interface{}
:
var migrations map[string]interface{}
json.Unmarshal(raw, &migrations)
fmt.Println(migrations["create_user"])
But I modified my code to point data to interface{}
: 但是我修改了我的代码以将数据指向
interface{}
:
var migrations interface{}
json.Unmarshal(raw, &migrations)
// compile wrong here
fmt.Println(migrations["create_user"])
I don't understand much about difference between map[string]interface{}
and interface{}
in above case. 在上面的例子中,我不太了解
map[string]interface{}
和interface{}
之间的区别。
The difference between those two types is just what it seems: 这两种类型之间的差异正是它看起来:
interface{}
is the "any" type, since all types implement the interface with no functions. interface{}
是“any”类型,因为所有类型都实现了没有函数的接口。
map[string]interface{}
is a map whose keys are strings and values are any type. map[string]interface{}
是一个映射,其键是字符串,值是任何类型。
When unmarshaling a byte array from JSON into memory it's easiest to use the interface{}
type, since it can store any type of JSON document (objects, arrays, primitives, etc.); 当将一个字节数组从JSON解组到内存中时,最简单的方法是使用
interface{}
类型,因为它可以存储任何类型的JSON文档(对象,数组,基元等); however, it may require more reflection to handle the underlying data. 但是,它可能需要更多的反射来处理底层数据。 Using a
map[string]interface{}
is common when you know the JSON document is an object and []interface{}
is common when you know the document is an array. 当您知道JSON文档是对象时,使用
map[string]interface{}
很常见,当您知道文档是数组时, []interface{}
很常见。
However, the best approach for unmarshaling JSON - especially when you know the structure of the documents ahead of time - is to define and use custom struct types that describe the data exactly. 但是,解组JSON的最佳方法 - 特别是当您提前知道文档的结构时 - 是定义和使用完全描述数据的自定义结构类型。 This way you can avoid any reflection and improve the legibility of your code.
这样您就可以避免任何反射并提高代码的易读性。
It is because by default you need to type assert interface{} to get the underlying value of map[string]interface{}. 这是因为默认情况下,您需要键入assert interface {}以获取map [string] interface {}的基础值。
As per GoLang Specification 根据GoLang规范
For an expression x of interface type and a type T, the primary expression
对于接口类型的表达式x和类型T,主表达式
x.(T)
asserts that x is not nil and that the value stored in x is of type T. The notation x.(T) is called a type assertion.
声明x不是nil并且存储在x中的值是T类型。符号x。(T)称为类型断言。
Also Unmarshal
function requires pointer to migration
of type interface{} or map[string]interface{} Unmarshal
函数也需要指向类型interface {}或map [string] interface {}的migration
的指针
var migrations interface{}
json.Unmarshal(raw, &migrations)
fmt.Println(migrations.(interface{}).(map[string]interface{})["create_user"])
Since migrations
is not a map. 由于
migrations
不是地图。 So you cannot use its key to get the value. 所以你不能用它的钥匙来获得价值。 Interface{} don't have keys
接口{}没有密钥
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.