How is a blank interface different from a generic one?

I may not fully understand the power of generics, but how interface{}

does an empty interface differ from a generic one, especially if we have the ability to use reflection or type switches? People always mention that Go has no generics, but interface{}

it looks like this work is comparable to something like <T>

Java.

+3


source to share


1 answer


If you come from Java, the empty interface ( interface{}

) is actually closer to working with variables Object

in Java than generics.

You can assign anything to interface{}

(for example, you can use a variable Object

in Java).

But then you have to "throw" or "type assertion" if you want to use the actual type you store there (the same thing you do with variables Object

in Java).

Generics in Java are quite different because they allow type checking to be preserved at compile time. Miscellaneous is exactly what you don't need to resort to reflection or type switches if you're working with Generics.



You can read more about Java generics here:

https://docs.oracle.com/javase/tutorial/java/generics/

And then follow this and the next 2 or 3 Tour Go steps here to learn more about how a blank interface works:

https://tour.golang.org/methods/14

+6


source







All Articles