Methods in Go

Go: Methods

Go supports methods defined on struct types.

How to define a method in Go:

    type Rectangle struct {
        Width  float64
        Height float64
    }

    func (r Rectangle) Area() float64 {
        return r.Width * r.Height
    }

Call the method

To call the method, we can use the dot notation, like below

    r := Rectangle{Width: 10, Height: 5}
    area := r.Area()
    fmt.Println(area)    // Output: 50

Define methods with pointer receivers -

This allow you to modify the fields of the struct.

    func (r *Rectangle) Scale(factor float64) {
        r.Width *= factor
        r.Height *= factor
    }

    r := Rectangle{Width: 10, Height: 5}
    r.Scale(2)
    fmt.Println(r)    // Output: {20 10}

Previous Article

Next Article