[英]Why converting interface{} to uint32 doesn't work even when the actual value is in the range of uint32
I'm trying to retrieve a value from a YAML string and store it as uint32
using gopkg.in/yaml.v2 .我正在尝试从 YAML 字符串中检索值并使用gopkg.in/yaml.v2将其存储为
uint32
。
When I try to convert a value foo
as follows, I get an error message that says: panic: interface conversion: interface {} is int, not uint32
.当我尝试按如下方式转换值
foo
,我收到一条错误消息: panic: interface conversion: interface {} is int, not uint32
。 I can't understand the reason why I see the error message, because the value foo
is actually 3
and it's in the range of uint32
.我不明白为什么我会看到错误消息,因为值
foo
实际上是3
并且它在uint32
的范围内。
var myYaml = `
foo: 3
`
type SampleYaml struct {
Foo interface{}
}
func main() {
var sampleYaml SampleYaml
var uint32Val uint32
yaml.Unmarshal([]byte(myYaml), &sampleYaml)
uint32Val = sampleYaml.Foo.(uint32)
fmt.Println(uint32Val)
}
Here's the actual code that I'm struggling with.这是我正在努力解决的实际代码。
From the spec:从规范:
If T from v.(T) is not an interface type then such assertion checks if dynamic type of v is identical to T
如果来自 v.(T) 的 T 不是接口类型,那么这样的断言检查 v 的动态类型是否与 T 相同
When you do type assertion the dynamic type of v has to be identical to T, according to your error message the dynamic type is int
and you're trying to assert it to uint32
that won't work since they are not identical.当您进行类型断言时,v 的动态类型必须与 T 相同,根据您的错误消息,动态类型是
int
并且您试图将其断言为uint32
,因为它们不相同,因此不起作用。
You probably want to do something like this:你可能想做这样的事情:
uint32Val = uint32(sampleYaml.Foo.(int))
You first use type assertion to get an int
from your interface{}
and then you use type coercion to have your uint32
您首先使用类型断言从您的
interface{}
获取一个int
,然后您使用类型强制让您的uint32
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.