golang`range`关键字是否为类型信息?

时间:2015-01-30 16:05:35

标签: go

考虑一下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

1 个答案:

答案 0 :(得分:4)

range返回的第一个值是索引,而不是值。你需要的是:

func main() {
    one := uint(1)
    ones := []uint{1, 1, 1}
    for _, x := range ones {
        if x != one {
            print("ERR")
        }
    }
}