Methods for all types

yourbasic.org/golang

Any type declared in a type definition can have methods attached.

In this example, the Value method is associated with MyType. The method receiver is called p.

type MyType struct {
    n int
}

func (p *MyType) Value() int { return p.n }

func main() {
    pm := new(MyType)
    fmt.Println(pm.Value()) // 0 (zero value)
}

If you convert the value to a different type, the new value will have the methods of the new type, not those of the old type.

type MyInt int

func (m MyInt) Positive() bool { return m > 0 }

func main() {
    var m MyInt = 2
    m = m * m // The operators of the underlying type still apply.

    fmt.Println(m.Positive())         // true
    fmt.Println(MyInt(-1).Positive()) // false

    var n int
    n = int(m) // The conversion is required.
    n = m      // ILLEGAL
}
../main.go:14:4: cannot use m (type MyInt) as type int in assignment