英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论