考虑一下golang程序:
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)
为什么认为x
类型为int
而不是uint
?
答案 0 :(得分:4)
range
返回的第一个值是索引,而不是值。你需要的是:
func main() {
one := uint(1)
ones := []uint{1, 1, 1}
for _, x := range ones {
if x != one {
print("ERR")
}
}
}