0

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 ?

blackgreen
  • 34,072
  • 23
  • 111
  • 129
George
  • 3,521
  • 4
  • 30
  • 75
  • 2
    "Package builtin provides documentation for Go's predeclared identifiers. The items documented here are not actually in package builtin but their descriptions here allow godoc to present documentation for the language's special identifiers." – Ry- Jun 15 '17 at 12:38
  • 1
    It's a nice try, but Go really, genuinely *does not have generics*. The built-in functions are built-in and handled by the compiler, not the stdlib, and are not limited to functionality available in the Go language itself. – Adrian Jun 15 '17 at 13:49

1 Answers1

5

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

Community
  • 1
  • 1
icza
  • 389,944
  • 63
  • 907
  • 827