[英]Golang Type Assertion Arrays
For what I understand type assertion can only be used in interfaces and basically check if a determined type implements the interface.据我所知,类型断言只能在接口中使用,并且基本上检查确定的类型是否实现了接口。
I am having some weird scenarios:我有一些奇怪的场景:
func binder(value interface{}) {
// Does not work
valueInt, ok := value.(int)
// Works
valueInt, ok := value.(float64)
// Does not work
coordinates, ok := value.([]int)
// Does not work
coordinates, ok := value.([]float64)
}
Basically, my value
is an empty interface and I am getting from a json.Unmarshall
.基本上,我的
value
是一个空接口,我从json.Unmarshall
。
Scenario 1场景一
when I pass a simple integer it does not work but if I check if is a float it works...当我传递一个简单的整数时它不起作用但是如果我检查它是否是一个浮点数它会起作用......
Scenario 2场景二
When I pass an array of int or floats does not work!当我传递一个 int 或 floats 数组时不起作用! As you can see when I am debugging I am receiving an array but for some reason assertion does not work.
正如您在调试时所看到的,我正在接收一个数组,但由于某种原因断言不起作用。
Your question is unclear, but it appears to boil down to the following:你的问题不清楚,但似乎归结为以下几点:
By default, json.Unmarshal
unmarshals all numbers into float64, since all numbers in JSON are floats.默认情况下,
json.Unmarshal
所有数字解组为 float64,因为 JSON 中的所有数字都是浮点数。 If you want some other type, you need to use a specific type in your target type.如果需要其他类型,则需要在目标类型中使用特定类型。 Examples:
例子:
var x map[string]interface{}
json.Unmarshal([]byte(`{"foo":123}`), &x) // { "foo": float64(123) }
vs:对比:
var x map[string]int64
json.Unmarshal([]byte(`{"foo":123}`), &x) // { "foo": int64(123) }
And by default, all JSON arrays unmarshal to []interface{}
, because the members can be of any type, including mixed types.默认情况下,所有 JSON 数组都解组为
[]interface{}
,因为成员可以是任何类型,包括混合类型。 If you want a specific type, again, you have to be specific:如果你想要一个特定的类型,同样,你必须是特定的:
var x interface{}
json.Unmarshal([]byte(`[1,2,3]`), &x) // []interface{}{float64(1), float64(2), float64(3)}
vs:对比:
var x []int64
json.Unmarshal([]byte(`[1,2,3]`), &x) // []int64{1,2,3}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.