Go by Example: Methods

Methods in Go are functions that are associated with a specific type or struct. Methods can be defined on types including built-in types like int or string, or on structs.

Here’s an example of a method defined on a struct:

package main

import "fmt"

type rect struct {
    width, height int
}

func (r *rect) area() int {
    return r.width * r.height
}

func (r rect) perim() int {
    return 2*r.width + 2*r.height
}

func main() {
    r := rect{width: 10, height: 5}

    fmt.Println("area: ", r.area())
    fmt.Println("perim:", r.perim())

    rp := &r
    fmt.Println("area: ", rp.area())
    fmt.Println("perim:", rp.perim())
}

In this example, the struct rect has two methods, area and perim, both of which return values based on the width and height of the rect. The area method is defined with a pointer receiver, meaning it can modify the fields of the rect, while the perim method is defined with a value receiver, meaning it can access the fields of the rect but not modify them.

In the main function, two variables of type rect are created, and the methods are called on both the struct value and its pointer. The output will be:

area:  50
perim: 30
area:  50
perim: 30

Here’s another example that demonstrates how methods can be used to encapsulate behavior and data within a single type:

package main

import "fmt"

type Circle struct {
    radius float64
}

func (c Circle) Area() float64 {
    return 3.14159265358979323846 * c.radius * c.radius
}

func (c *Circle) Scale(factor float64) {
    c.radius *= factor
}

func main() {
    c := Circle{radius: 5}
    fmt.Println("Circle area:", c.Area())
    c.Scale(2)
    fmt.Println("Scaled Circle area:", c.Area())
}

In this example, we have a Circle struct with a single field, radius. Two methods are defined on this struct, Area and Scale. Area returns the area of the circle, while Scale changes the radius of the circle by a factor.

In the main function, we create an instance of Circle and call its methods. The output will be:

Circle area: 78.53975
Scaled Circle area: 314.1592653589793

As you can see, methods provide a convenient way to encapsulate behavior and data within a single type, making it easier to organize and reason about complex code.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *