doubei8541 2018-02-28 16:01
浏览 379
已采纳

为什么即使实际值在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.

  • 写回答

1条回答 默认 最新

  • dongxi8993 2018-02-28 17:16
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度