How does signature of builtin.append() make any sense?

Append has a signature of …

type Type int

func append(slice []Type, elems ...Type) []Type {
	return nil

In practical use how does a method that accepts a type that’s an int do the following …

  • accept any type other than int
  • assert a constraint that slice/elems and the return value share a common type?

I could understand if it looked more like this …

func append1(slice []Type1, elems ...Type1) []Type1 {

Doesn’t make any sense to me.

Hi @Johnlon,

The Go source code solves this riddle:

// Type is here for the purposes of documentation only. It is a stand-in
// for any Go type, but represents the same type for any given function
// invocation.
type Type int

So append does not really operate on []int slices and int elements. The compiler adjusts append to the actual type, just as if append was a generic function.


How do I take advantage of same capability?

append is actually a special function that is part of Golang’s feature that you can’t write on your own. It’s already builtin inside the compiler. I think, internally, Golang convert append to runtime.growslice and pass the underlying pointer, cap, len and pointer to its element type (this pointer is not directly accessible by us).

The function signature of append is not an actual function signature. It’s just a trick to make the documentation shows something when you hover the append.

Well, you can’t. It’s a language feature. Append is special, just like make, cap, len.
You can, however, use generic to get similar capability, but not exactly the same.