Golang中For循环的歧义行为 [英] Ambiguous behavior of For loop in Golang

查看:109
本文介绍了Golang中For循环的歧义行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做一些简单的循环,像这样:

package main

import "fmt"

func main() {
    var i uint32 // code bellow works fine with int32
    for i = 31; i >= 0; i-- {
        fmt.Println(i)
    }
}

但是,如果i具有类型uint32,则此循环是无限的.如果iint32可以.

如果i的类型为uint32而不检查if i == 0,如何中断此循环?

解决方案

i的类型为uint32,因此一旦达到0,再次递减将导致uint32的最大值.更改循环条件以进行检查:

var i uint32 // code bellow works fine with int32
for i = 31; i != 0xffffffff; i-- {
    fmt.Println(i)
}

游乐场上尝试.

或使用math.MaxUint32常量:

var i uint32 // code bellow works fine with int32
for i = 31; i != max.MaxUint32; i-- {
    fmt.Println(i)
}

或者使用^uint32(0)表达式,其中^运算符是按位补数运算符,应用于0会为您提供一个所有位均为1的值:uint32的最大值.

尽管您看了一下代码,但它并不直观,难以理解.因此,您应该使用不需要且更简单的替代方法,例如使用int32并检查i >= 0,或使用向上循环,例如:

for i := uint32(0); i < 32; i++ {
    fmt.Println(31 - i)
}

或将循环变量的范围偏移+1,因此您可以测试i >= 1i > 0:

for i := uint32(32); i > 0; i-- {
    fmt.Println(i-1)
}

I want make some simple loop like this:

package main

import "fmt"

func main() {
    var i uint32 // code bellow works fine with int32
    for i = 31; i >= 0; i-- {
        fmt.Println(i)
    }
}

But this loop is endless, if i has type uint32. If i is int32 it`s ok.

How I can break this loop, if i has type uint32 without checking if i == 0?

解决方案

i is of type uint32, so once it reaches 0, decrementing again will result in the max value of uint32. Change the loop condition to check for that:

var i uint32 // code bellow works fine with int32
for i = 31; i != 0xffffffff; i-- {
    fmt.Println(i)
}

Try it on the Go Playground.

Or use the math.MaxUint32 constant:

var i uint32 // code bellow works fine with int32
for i = 31; i != max.MaxUint32; i-- {
    fmt.Println(i)
}

Or use the ^uint32(0) expression, where the ^ operator is the bitwise complement operator, applied on 0 will give you a value where all the bits are ones: the max value for uint32.

Although if you look at the code, it's not intuitive, hard to understand. So you should use alternatives where this is not required and are more straightforward, such as using int32 and checking for i >= 0, or use an upward loop, such as:

for i := uint32(0); i < 32; i++ {
    fmt.Println(31 - i)
}

Or offset the loop variable's range with +1, so you can test for i >= 1 or i > 0:

for i := uint32(32); i > 0; i-- {
    fmt.Println(i-1)
}

这篇关于Golang中For循环的歧义行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆