Go: Methods explained

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

type MyType struct {
        n int

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

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

This declares a method Value associated with MyType. In this case, the receiver is named p in the body of the function.

You may define methods on any type declared in a type definition. 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())         // Output: true
        fmt.Println(MyInt(-1).Positive()) // Output: 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


Be the first to comment!