Tuesday, August 9, 2022

On Go's Interfaces and Generics

Go Interfaces: Calling Site Polymorphism

The signatures remain constant, the bodies of methods vary.
  1. A Go interface defines a set of method signatures
  2. Any type that defines that full complement of methods is said to implement that interface.
  3. Variables of that interface type provides a level of indirection to values of types that implement that interface.
  4. Callers use these variables for dispatching an interface method to the corresponding method of underlying value.
The benefit of a Go interface is calling site polymorphism. The same call site can invoke the methods of any type implementing the interface. The benefits allow the calling site to use less code and require less maintenance over time.

Go Generics: Called Site Polymorphism

The signatures vary, the bodies of functions remain constant.
  1. A Go function body may be parameterized by one or more type parameters ("generics").
  2. A generic function may be instantiated with corresponding types that satisfy the constraints of the type parameters.
  3. The result is a non-generic function for the specific types using the body of the generic function.
  4. Multiple instantiations with differing sets of types result in multiple non-generic functions with the same body.
The benefit of Go generics is called site polymorphism. The same called site (function definition) can be instantiated by any types satisfying the type constraints. The benefits allow the called site to use less code and require less maintenance over time.

Conclusion

Calling site polymorphism and called site polymorphism serve distinct purposes. One does not replace the other in whole or in part.

No comments:

Post a Comment