英文:
How can I change the for loop iterator type?
问题
Go在默认情况下使用int作为迭代器,但我想要使用uint64。我无法找到一种方法来改变Go中for循环迭代器的类型。有没有一种方法可以在for语句中内联地进行更改?当我尝试在循环中执行一些操作,比如取模运算(%)时,默认的int类型会引起问题。
func main() {
var val uint64 = 1234567890
for i := uint64(1); i < val; i += 2 {
if val%i == 0 {
}
}
}
./q.go:7: invalid operation: i < val (mismatched types int and uint64)
./q.go:8: invalid operation: val % i (mismatched types uint64 and int)
英文:
Go uses int for the iterator by default from what I can tell, except I want uint64. I cannot figure out a way to change the type of for loop iterator in Go. Is there a way to do it inline with the for statement? The default type of int causes problems when I try to do something in the loop, like a mod operation (%).
func main() {
var val uint64 = 1234567890
for i:=1; i<val; i+=2 {
if val%i==0 {
}
}
}
./q.go:7: invalid operation: i < val (mismatched types int and uint64)
./q.go:8: invalid operation: val % i (mismatched types uint64 and int)
答案1
得分: 37
你是指像这样的吗?
for i, val := uint64(1), uint64(1234567890); i<val; i+=2 {
// 你的模运算
}
http://play.golang.org/p/yAdiJu4pNC
英文:
You mean something like this?
for i, val := uint64(1), uint64(1234567890); i<val; i+=2 {
// your modulus operation
}
答案2
得分: 0
另一个选项是使用“while”循环:
package main
func main() {
var i, val uint64 = 1, 1234567890
for i < val {
if val % i == 0 {
println(i)
}
i += 2
}
}
https://golang.org/ref/spec#For_condition
英文:
Another option is to use a "while" loop:
package main
func main() {
var i, val uint64 = 1, 1234567890
for i < val {
if val % i == 0 {
println(i)
}
i += 2
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论