dpdp42233 2019-09-24 02:22
浏览 93
已采纳

将零int声明为int32

I noticed that Go assertion doesn't work as I expect for zero int. Here is the code:

var i interface{}
i = 0
i32, ok := i.(int32)
fmt.Println(ok)
fmt.Println(i32)

The output is following:

false
0

I can't find an explanation of this behavior. Is it a bug?

  • 写回答

2条回答 默认 最新

  • dooid3005 2019-09-24 02:32
    关注

    No, it's not a bug, it's a well defined behavior.

    This line:

    i = 0
    

    Is an assignment, and you use the untyped 0 integer constant to assign to i. Since a (concrete) type is needed to carry out the assignment (and is type being interface{} does not define one), the default type of that untyped constant will be used which is int. Read The Go Blog: Constants:

    The answer is that an untyped constant has a default type, an implicit type that it transfers to a value if a type is needed where none is provided.

    You can verify it if you modify it like this:

    i2, ok := i.(int)
    fmt.Println(ok)
    fmt.Println(i2)
    

    Which outputs:

    true
    0
    

    If you would use a typed constant:

    i = int32(0)
    

    Then yes, the stored value would be of type int32, and you would get the same output:

    i = int32(0)
    i32, ok := i.(int32)
    fmt.Println(ok)
    fmt.Println(i32)
    

    Try the examples on the Go Playground.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题