0
0
Goprogramming~5 mins

Method call behavior in Go

Choose your learning style9 modes available
Introduction

Methods let you do actions with data stored in a type. Understanding how method calls work helps you write clear and correct programs.

When you want to perform an action related to a specific data type.
When you want to change the data inside a type using a method.
When you want to read data from a type without changing it.
When you want to organize code by grouping functions with data.
When you want to understand how Go handles method calls with pointers and values.
Syntax
Go
func (receiver Type) MethodName(params) returnType {
    // method body
}

The receiver is like the object the method works on.

Receivers can be values or pointers, which affects if the method can change the original data.

Examples
This method uses a value receiver. It cannot change the original Person.
Go
type Person struct {
    name string
}

func (p Person) Greet() string {
    return "Hello, " + p.name
}
This method uses a pointer receiver. It can change the original Person data.
Go
func (p *Person) ChangeName(newName string) {
    p.name = newName
}
Shows calling methods with value and pointer receivers on a Person variable.
Go
p := Person{name: "Alice"}
fmt.Println(p.Greet())
p.ChangeName("Bob")
fmt.Println(p.Greet())
Sample Program

This program shows how methods with value and pointer receivers behave differently. The Increment method changes the original Counter because it uses a pointer receiver.

Go
package main

import "fmt"

type Counter struct {
    count int
}

// Method with value receiver: cannot change original
func (c Counter) Display() {
    fmt.Println("Count is", c.count)
}

// Method with pointer receiver: can change original
func (c *Counter) Increment() {
    c.count++
}

func main() {
    c := Counter{count: 5}
    c.Display()       // prints 5
    c.Increment()     // increases count
    c.Display()       // prints 6
}
OutputSuccess
Important Notes

Using a pointer receiver lets the method change the original data.

Using a value receiver means the method works on a copy and cannot change the original.

Go lets you call pointer methods on values and value methods on pointers; it handles conversion automatically.

Summary

Methods are functions tied to a type using receivers.

Pointer receivers allow methods to modify the original data.

Value receivers work on copies and cannot change the original data.