Go – 在for循环条件中使用uint32(类型不匹配 int 和 uint32)

huangapple go评论85阅读模式
英文:

Go - uint32 in for loop condition (mismatched types int and uint32)

问题

为了严格控制类型,当大小不能为负时,我有时将大小存储为uint。当在for循环中使用时,我希望它看起来像这样:

var size uint32 = 8
for i := 0; i < size; {
    n := //不管如何确定这个值
    i += n
}

然而,我得到以下错误信息:invalid operation: i < size (mismatched types int and uint32)

将for循环重写为指定类型,像这样:

for var i uint32 = 0; i < size; {

会产生编译器错误:syntax error: var declaration not allowed in for initializer

唯一的解决方法是:

for i := 0; uint32(i) < size; {

或者

var i uint32 = 0
for i < size {

第一种方法效率低下,因为我在每次迭代时都要进行类型转换,而第二种方法不够优雅。有没有更好的方法来解决这个问题?

英文:

For the sake of type strictness I sometimes store my sizes as uint's when a size cannot be negative. When used in for loops, I want it to look like this:

var size uint32 = 8
for i := 0; i &lt; size; {
    n := //doesn&#39;t matter how how this value is determined
    i += n
}

However, I get the following error message: invalid operation: i &lt; size (mismatched types int and uint32)

Rewriting the for loop to specify a type like this:

for var i uint32 = 0; i &lt; size; {

Yields this compiler error: syntax error: var declaration not allowed in for initializer

The only ways around these errors are:

for i := 0; uint32(i) &lt; size; {

or

var i uint32 = 0
for i &lt; size {

The first on is inefficient because I am casting on every iteration and the second one is less elegant. Is there a better way to do this?

答案1

得分: 43

你可以这样做:

for i := uint32(0); i < size; {
    //无论如何
}

一般来说,即使size永远不会为负数,我也不建议使用无符号整数。我不知道有什么好处。我只在有意溢出时使用无符号整数。

英文:

You can do:

for i := uint32(0); i &lt; size; {
    //whatever
}

Generally, I don't recommend using an unsigned integer even when size can never be negative. I don't know of any upside. I only use unsigned integers when I am intentionally overflowing.

huangapple
  • 本文由 发表于 2012年11月15日 01:25:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/13383951.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定