How is the empty interface different than a generic?

Viewed 5570

Maybe I'm not fully versed on the power of generics, but how is the empty interface, interface{}, different than a generic, especially if we have the ability to use reflection or type switches? People always mention that Go doesn't have generics, but interface{} seems like it does the job pretty comparable to something like <T> in Java.

2 Answers

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.

Related