Golang范围类型转换

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

Golang range type conversion

问题

我对我拥有的这段代码感到非常困惑:

docs, ok := foo.([]interface {})
if !ok{ panic("assertion failed") }

fmt.Println("The type of docs: ", reflect.TypeOf(docs))
for _, doc := range docs {
    fmt.Println("Doc Type: ", reflect.TypeOf(doc))
}

当我运行这段代码时,输出结果是:

The type of docs: []interface {}
Doc type: bson.D

我不明白。我将foo类型断言为[]interface{}并将其存储在docs中。这符合预期,但是在循环中,我打印出的第一件事是doc的类型,它显示为bson.D。为什么不是interface {}?我甚至将doc的名称更改为bar,以为可能是作用域问题之类的,但结果还是一样的。

英文:

I'm very confused by this code that I have:

docs, ok := foo.([]interface {})
if !ok{ panic("assertion failed") }

fmt.Println("The type of docs: ", reflect.TypeOf(docs))
for _, doc := range docs {
    fmt.Println("Doc Type: ", reflect.TypeOf(doc))
}

The output when I run this is:

The type of docs: []interface {}
Doc type: bson.D

I don't get it. I type assert foo to []interface{} and store it in docs. That works as expected, but then in the loop, the first thing I print out is the type of doc and it says it's bson.D. How is it not interface {}?? I even changed the name of doc to bar thinking maybe it was a scoping issue or something, but I get the same results.

答案1

得分: 3

TypeOf文档中写道:TypeOf返回interface{}中值的反射类型。TypeOf(nil)返回nil。

所以doc的类型是interface{},但是TypeOf返回它的“真实”类型。

英文:

TypeOf documentation says: TypeOf returns the reflection Type of the value in the interface{}. TypeOf(nil) returns nil.

So doc is of type interface{} but TypeOf returns its "true" type.

huangapple
  • 本文由 发表于 2015年1月20日 04:58:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/28033358.html
匿名

发表评论

匿名网友

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

确定