Go methods on non-local types
We cannot add methods to non-local types, that is, types not defined in our package.
We can however create a new type that inherits from the type we want to add the method too:
1type MyInt int
Now, MyInt
is a local type we can add methods to.
1func (i MyInt) Twice() MyInt {
2 return i * 2
3}
Careful that Go considers int
and MyInt
two distinct types. You can’t pass an int
value where a MyInt
is expected, and vice versa.
This means we have to convert int
s to MyInt
s using type conversion:
1input := MyInt(9)
Not every type conversion is possible.
References
- go-struct-wrappers
- John Arundel, For the Love of Go
Next -> go-struct-wrappers
#types #golang #methods #non_local #programming #custom #receiver #local