Builtin functions with user type definition

I am unclear on the rules around when builtin functions can be used with user defined types. In particular, if I create a type like type T1 []int, where would I look to learn that I can use append with type T1?

Hi @kanishka, welcome to the forum.

The append builtin works for slices, and T1 is type whose underlying type is a slice, hence append works with T1 as well.

In general, if a builtin function works for a particular type, and a custom type has that type as its underlying type, the builtin function should work for that type as well.

For questions around particular core language features, the Go Language Reference is your friend, if you don’t mind searching around a bit and connecting the different pieces.

For example, append is described here (among other builtins) and custom types and underlying types are mentioned here (in subsection “Type definitions”).

And if in doubt, try it out…

2 Likes

I am surprised that this compiles without an explicit conversion:

type Int32Set map[int32]bool

func NewInt32Set() Int32Set {
    return make(map[int32]bool)
}

Also works

return make(Int32Set)

This is covered by the assignability rules of the language specification, especially:

A value x is assignable to a variable of type T (“xis assignable to T”) if one of the following conditions applies:

  • …
  • x’s type V and T have identical underlying types and at least one of V or T is not a defined type.
  • …

In your case, x’s type V is map[int32]bool (not a defined type) and T is Int32Set, whose underlying type is map[int32]bool, so the above condition does apply.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.