Reputation: 4681
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.
Upvotes: 1
Views: 1151
Reputation: 4231
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.
Upvotes: 3