Go Generic Functions



In static programming languages, the term generic functions refers to some mechanism for compile-time polymorphism. this functions with defined TypeParameters, intended for the compiler to be resolved during compile time the type information provided by the user.

how does it look

Other Programming Language Implementation

// C#/Typescript
static void SortList<T>(List<T> items) List<T>
// c++ 
// template
template<typename T> 
void f(T s) { 
    std::cout << s << '\n';
// rust
fn generic<T>(_s: SGen<T>) {}

Go using Contracts

func Stringify(type T stringer)(s []T) (ret []string) {

status of go

it’s far from being finish. with current discussion and proposal, it’s way way far. obviously, go creators doesn’t like complicate things. it’s keeping the language very simple. this are the questions linger to one of it’s core dev/blog.

First, does generic code make sense? Does it feel like Go? What surprises do people encounter? Are the error messages useful?
Second, we know that many people have said that Go needs generics, but we don’t necessarily know exactly what that means. Does this draft design address the problem in a useful way? If there is a problem that makes you think “I could solve this if Go had generics,” can you solve the problem when using this tool?

this has advantages and disadvantages of course.

Key benefits of generic functions

  1. code reusability
  2. avoid code duplication
  3. avoid function overloading
  4. readability
    and more…

some examples from Go

sorting string and int

this is how to sort ints

func ReverseInts(s []int) {
    first := 0
    last := len(s)
    for first < last {
        s[first], s[last] = s[last], s[first]

this is how to sort strings

func ReverseStrings(s []string) {
    first := 0
    last := len(s) - 1
    for first < last {
        s[first], s[last] = s[last], s[first]

almost identical. we have lots of this in our codebase too… it’s not avoidable, but can be avoided if we follow practices, like what captain rob pike says

If C++ and Java are about type hierarchies and the taxonomy of types, Go is about composition. (Rob Pike)

this is true. we can use interface, type assertions, or reflections. but use this with a grain of salt or else interface {} is not string panic


we will knew, later this year or next? we don’t know.

Early Conclusion

If ever you worked on systems programming language for a very long time, 10years+ like me, you’ll miss fundamental features that could allow developers like us to be more productive by many factors including the ability to reduce the amount of codes to be written, and could make the code easier to use and read.

this goes out of the window if you worked in Go. but consider this also as a not bad feature. go is still far beyond early comparing with c/c++/c#/java. go doesn’t rely on just this. it has so many strengths and unique features that many developers love.

1 Like