golang的`range`关键字是否会破坏uint类型的信息?

huangapple go评论82阅读模式
英文:

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(&quot;ERR&quot;)
        }
    }
}

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(&quot;ERR&quot;)
        }
    }
}

huangapple
  • 本文由 发表于 2015年1月31日 00:05:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/28239911.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定