How is the empty interface different than a generic?
If you come from Java, the empty interface (interface{}
) is actually closer to working with Object
variables in Java than with generics.
You can assign anything to an interface{}
(like you can do with an Object
variable in Java).
But you should then "cast" or "type assert" back if you want to use the actual type you stored there (same that you need to do with Object
variables in Java).
Generics in Java are quite different, since they allow you to keep type checking at compile time. The difference is precisely that you don't need to resort to reflection or type switches if you work 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 steps of the Go tour here for more on how the empty interface works:
https://tour.golang.org/methods/14
Considering the main point of generics is to maintain the compile-time type safety check for statically typed languages when providing facilities to write type agnostic functions/methods, the empty interface with runtime type assertions/switches is completely different from generics and I'd say it's almost the complete opposite to generics in terms of programming paradigms.
I'd say more than half of the programming language improvements over the last decade are about avoiding runtime errors, and I guess that's why Go has some "built-in generics" like slice and map instead of something like the old JavaScript's Array stuff which only has type checks on its elements during run-time. So the empty interface with type assertion/switch in Go is definitely no replacement for generics and personally, I'd try to avoid using the empty interface as much as possible.