douguio0185
douguio0185
2018-01-26 20:45

当变量可以时,不能将int32 const强制转换为uint32的原因是什么? [重复]

  • IT行业问题
  • 计算机技术
  • it技术
  • 编程语言问答
  • 互联网问答
已采纳

I've found that you can cast a variable int32 to uint32 but you cannot cast a const int32 to uint32.

See here: https://play.golang.org/p/tDm6B6g5P6u

If line 14 is commented out it works.

Does anyone have an explanation for this?

Thanks!

</div>
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • dtz33344 dtz33344 3年前

    The expression uint32(ci) is a constant expression. The spec says this about constant expressions:

    The values of typed constants must always be accurately representable as values of the constant type.

    A uint32 cannot accurately represent the negative value ci, therefore this expression results in a compilation error.

    Positive values in range are supported. For example, uint32(-ci) compiles with no error.

    The expressions uint32(vi) and uint32(vc) are conversions. Conversions betweeen numeric types are allowed, even when there's loss of accuracy.

    点赞 评论 复制链接分享