为什么即使实际值在uint32范围内,也无法将interface {}转换为uint32

I'm trying to retrieve a value from a YAML string and store it as uint32 using gopkg.in/yaml.v2.

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. 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.

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

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.

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