英文:
Does the golang `range` keyword botch uint type information?
问题
考虑以下这个Go语言程序:
func main() {
one := uint(1)
ones := []uint{1, 1, 1}
for x := range ones {
if x != one {
print("ERR")
}
}
}
当我尝试编译时,出现了一个意外的错误:
$ go build foo.go
# command-line-arguments
./foo.go:7: invalid operation: x != one (mismatched types int and uint)
为什么Go认为x
的类型是int
而不是uint
?
英文:
Consider this golang program:
<!-- language: lang-go -->
func main() {
one := uint(1)
ones := []uint{1, 1, 1}
for x := range ones {
if x != one {
print("ERR")
}
}
}
When I try to compile I get an unexpected error:
$ go build foo.go
# command-line-arguments
./foo.go:7: invalid operation: x != one (mismatched types int and uint)
Why does go think x
has type int
instead of uint
?
答案1
得分: 4
range
返回的第一个值是索引,而不是值。你需要的是:
func main() {
one := uint(1)
ones := []uint{1, 1, 1}
for _, x := range ones {
if x != one {
print("ERR")
}
}
}
range
返回的第一个值是索引,而不是值。你需要的是:
func main() {
one := uint(1)
ones := []uint{1, 1, 1}
for _, x := range ones {
if x != one {
print("ERR")
}
}
}
英文:
The first value returned by range
is the index, not the value. What you need is:
func main() {
one := uint(1)
ones := []uint{1, 1, 1}
for _, x := range ones {
if x != one {
print("ERR")
}
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论