4 ms·
> Whether it requires an allocation or not, it's an annoyance. This is just an example of behavior that is counterintuitive w.r.t interfaces. If I had a 1GB []
by jesstaa 15y ago
> Whether it requires an allocation or not, it's an annoyance. This is just an example of behavior that is counterintuitive w.r.t interfaces.
If I had a 1GB []byte and passed it in to a function taking an []interface{}. I think it would be really counterintuitive that the function call would allocate 16GB of memory. While passing it to a function taking a []byte would allocate no memory at all. You can't avoid this allocation.
It's been considered that it might be nice to be able to convert between slices of different interfaces and this might happen, but it's not going to happen for slices of types for the reason above.
The special case of auto-converting a type to an interface on assignment is a bit weird and creates endless confusion for new people coming from different language as it makes Go's interfaces look like they are the same as Java or C++'s. But once you understand it, then it makes sense.
In Java an Interface and an Object are very similar, they both have a set of virtual methods and interfaces just verify that the type you're passing in has the expected set of virtual methods to implement the interface. Converting an array of Java Objects to an array of Java interfaces doesn't require anything at runtime.
In Go, a type and an interface are very different, a type has static methods and an interface has virtual methods.
- barrkel 15y ago> Converting an array of Java Objects to an array of Java interfaces doesn't require anything at runtime. It potentially costs every time you put something into the array - Java arrays are covariant. Either a runtime check is needed, or the JIT compiler will have to create a proof that any particular array access is to a consistently typed array.
- DanWaterworth 15y agoI think I'm right in saying that haskell does what you'd expect when you have a list of some typeclass. The difference is that Go has opted to use RTTI, whereas haskell does it a compile time. So, it's not impossible to do well.