英文:
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 < size; {
n := //doesn't matter how how this value is determined
i += n
}
However, I get the following error message: invalid operation: i < size (mismatched types int and uint32)
Rewriting the for loop to specify a type like this:
for var i uint32 = 0; i < 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) < size; {
or
var i uint32 = 0
for i < 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 < 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论