Go Methods


Go methods are a powerful way to associate functions with specific data types (structs). They provide a mechanism for creating more organized and reusable code by encapsulating behavior within the types they operate on. This differs from regular functions which are defined independently.

Think of methods as functions that belong to a particular type. They have access to the data fields of the associated type, allowing you to manipulate and interact with the object’s internal state directly.

package main

import "fmt"

// Define a struct called Rectangle
type Rectangle struct {
    Width  float64
    Height float64
}

// Define a method `Area` that belongs to Rectangle
// The receiver is denoted by (r *Rectangle)
func (r *Rectangle) Area() float64 {
    return r.Width * r.Height
}

// Define another method `Perimeter`
func (r *Rectangle) Perimeter() float64 {
    return 2 * (r.Width + r.Height)
}


func main() {
    // Create an instance of the Rectangle struct
    rect := Rectangle{Width: 5, Height: 10}

    // Call the Area method on the rect instance
    area := rect.Area()
    fmt.Println("Area:", area) // Output: Area: 50

    // Call the Perimeter method
    perimeter := rect.Perimeter()
    fmt.Println("Perimeter:", perimeter) // Output: Perimeter: 30

     // Using pointer receivers allows modification of the original struct
    rect.Width = 7
    fmt.Println("New Area:", rect.Area())
}

Key Aspects of Go Methods:

Go methods are a fundamental aspect of object-oriented programming in Go, enabling you to write more structured, maintainable, and reusable code. They are powerful tools for encapsulating logic and working with custom data types efficiently.