Search code examples
gogccbuilt-in

Do Go built-ins use generics?


Looking at the builtins function of Go, I just realize that they don't use interfaces and instead use a magic 'Type'.

https://golang.org/src/builtin/builtin.go

So how exactly is this possible without using generics ? How would I write a function with a signature similar to append's (that takes an array of any type) without interfaces ?


Solution

  • It is not possible for you to create such functions. Functions that have this generic, magic "gene" are builtin functions covered by the language specification, listed in section Predeclared identifiers.

    Quoting from Effective Go: Append:

    The signature of append [...] schematically, it's like this:

    func append(slice []T, elements ...T) []T
    

    where T is a placeholder for any given type. You can't actually write a function in Go where the type T is determined by the caller. That's why append is built in: it needs support from the compiler.

    See related questions:

    Go functions accessed through variables

    Return map like 'ok' in Golang on normal functions