3 ms·
My String[] really is substitutable for an interface{}[] within the context of a function that doesn't modify it, but there seems no way to express this. Not r
by danieldk 14y ago
My String[] really is substitutable for an interface{}[] within the context of a function that doesn't modify it, but there seems no way to express this.
Not really. The underlying representation is different, an interface is a pointer to a type and a pointer to a value. A string is a pointer to the character data and a length.
It'd get even more difficult with other data types, since an interface is two machine words, and other data types can be anything. Since a slice is backed by an array, there would be no way to do reliable indexing.
I do see your point: a slice could hold the type of its elements and then you'd have to prove that no other types are stored in the slice. But that's not really simple either.
A more consistent solution would be to store 'interface values' as pointers (rather than a pair of pointers). Then you could use a slice of pointers as a slice of interface{} (or any other interface the pointed-to type supports).
- djhworld 14y ago> I do see your point: a slice could hold the type of its elements and then you'd have to prove that no other types are stored in the slice. But that's not really simple either. It's simple in typesafe languages that support generics/parametric polymorphism
- danieldk 14y agoIt's simple in typesafe languages that support generics/parametric polymorphism That's a different thing. The function is then instantiated to that particular type. []interface{} is more akin to an array of base class pointers. Except that in Go the type is stored with the pointer to the actual data.