0
0
Goprogramming~5 mins

Defining methods in Go

Choose your learning style9 modes available
Introduction

Methods let you add actions to your own types, like giving your data special abilities.

When you want to give a type a specific behavior, like making a shape calculate its area.
When you want to organize code so related actions are grouped with the data they work on.
When you want to change or use the data inside a type safely.
When you want to make your code easier to read by calling actions on objects.
When you want to reuse code by calling methods on different instances of a type.
Syntax
Go
func (receiver TypeName) MethodName(parameters) returnType {
    // method body
}

The receiver is like the object the method works on.

It can be a value or a pointer to the type.

Examples
This method calculates the area of a Circle type.
Go
func (c Circle) Area() float64 {
    return 3.14 * c.Radius * c.Radius
}
This method changes the Name field of a Person using a pointer receiver.
Go
func (p *Person) SetName(newName string) {
    p.Name = newName
}
Sample Program

This program defines a Rectangle type and a method Area that calculates its area. Then it creates a rectangle and prints its area.

Go
package main

import "fmt"

type Rectangle struct {
    Width, Height float64
}

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

func main() {
    rect := Rectangle{Width: 5, Height: 3}
    fmt.Println("Area of rectangle:", rect.Area())
}
OutputSuccess
Important Notes

Use pointer receivers if your method needs to change the data inside the type.

Use value receivers if your method only reads data and does not modify it.

Methods help keep your code organized and easy to understand.

Summary

Methods add actions to your own types.

Use receiver to connect method to a type.

Pointer receivers let methods change the original data.