drflkphi675447 2015-09-11 19:37
浏览 43
已采纳

我应该能够输入assert字符串映射的一部分吗?

I am receiving a message using the Go NSQ library where a field is a slice of map[string]string's. I feel like I should be able to type assert this field as value.([]map[string]string) but it's failing and I can't tell if this is expected or not.

This snippet replicates the behavior https://play.golang.org/p/qcZM880Nal

Why does this type assertion fail?

  • 写回答

2条回答 默认 最新

  • 普通网友 2015-09-11 19:48
    关注

    This is covered briefly here in the FAQ.

    The types []interface{} and []map[string]string have two different representation in memory. There is no direct way to convert between them.

    Also, even when a conversion is allowed, you should note that you can't successfully assert to a different basic type at all (http://play.golang.org/p/zMp1qebIZZ). You can only assert to the original type, or another type of interface,

    // panics
    var i interface{} = int32(42)
    _ = i.(int64)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?