尽管您看了一下代码,但它并不直观,难以理解.因此,您应该使用不需要且更简单的替代方法,例如使用int32并检查i >= 0,或使用向上循环,例如:for i := uint32(0); i < 32; i++ { fmt.Println(31 - i)}或将循环变量的范围偏移+1,因此您可以测试i >= 1或i > 0:for i := uint32(32); i > 0; i-- { fmt.Println(i-1)}I want make some simple loop like this:package mainimport "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 int32for 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 int32for 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循环的歧义行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 10-11 10:09