0
0
Goprogramming~5 mins

Pointer receivers in Go

Choose your learning style9 modes available
Introduction

Pointer receivers let methods change the original data inside a struct. They also avoid copying big data when calling methods.

When you want a method to modify the original struct data.
When your struct is large and copying it would be slow.
When you want to share the same data between methods without making copies.
When you want to keep method behavior consistent for both pointer and value types.
Syntax
Go
func (p *TypeName) MethodName(params) returnType {
    // method body
}

The receiver is written as a pointer: *TypeName.

This means the method works with the original struct, not a copy.

Examples
This method increases the count inside the original Counter struct.
Go
type Counter struct {
    count int
}

func (c *Counter) Increment() {
    c.count++
}
This method sets the count back to zero on the original struct.
Go
func (c *Counter) Reset() {
    c.count = 0
}
Sample Program

This program shows how pointer receivers let methods change the original struct data. Increment increases the count, Reset sets it back to zero.

Go
package main

import "fmt"

type Counter struct {
    count int
}

func (c *Counter) Increment() {
    c.count++
}

func (c *Counter) Reset() {
    c.count = 0
}

func main() {
    c := Counter{}
    fmt.Println("Initial count:", c.count)
    c.Increment()
    fmt.Println("After increment:", c.count)
    c.Reset()
    fmt.Println("After reset:", c.count)
}
OutputSuccess
Important Notes

If you use a value receiver instead, methods work on a copy and changes won't affect the original struct.

Pointer receivers are common when your method needs to modify the struct or when the struct is large.

Summary

Pointer receivers let methods change the original struct data.

They avoid copying the struct when calling methods.

Use pointer receivers when you want to modify data or improve performance.