What's the reason for having methods outside the definition of the struct?

Issue

Why do we have the methods declared outside the type definition of the struct? E.g.:

type antenna struct {
    name string
    length float32
    girth float32
    bloodtype string
}

func (p *antenna) extend() {
    p.length += 10
}

It seems to me that the method could be part of the struct? (Let’s ignore for now that structs are supposed to be value types)

type antenna struct {
    name string
    length float32
    girth float32
    bloodtype string

    func extend() {
        length += 10
    }
}

This would be more similar to traditional OOP. I didn’t find any good explanations of why it is done the way it is besides “structs are value-types and classes are reference-types”. I know the difference, but it’s not a satisfactory answer to me. In any way the method has to be called like this:

var x = antenna()
x.extend() 

So what’s the point of separating the the struct and methods? Having them visually grouped together in the code – as in typical OOP languages – seems useful to me?

Solution

By design this makes the Go language consistent for user defined struct with fields (see the following example #2) and named type (see the following example #1):

1- You may define your own types, See this example – There is no inside here for this named type – so methods must be outside of this type:

package main

import "fmt"

type num int32

func (p *num) inc() {
    *p++
}

func main() {
    p := num(100)
    p.inc()
    fmt.Println(p) // 101
}

2 – User defined type:


type Animal struct {
    Name  string
    moves []move.Direction
}

func (p *Animal) Walk(dir move.Direction) {
    p.moves = append(p.moves, dir)
}

See also:
In Go is naming the receiver variable 'self' misleading or good practice?

Answered By – wasmup

Answer Checked By – Katrina (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.