0
0
Goprogramming~5 mins

Value receivers in Go

Choose your learning style9 modes available
Introduction

Value receivers let you use a copy of a value when calling a method. This means the original value stays safe and unchanged.

When you want to make sure the original data does not change inside the method.
When your data is small and copying it is cheap and fast.
When you want to call methods on values, not pointers.
When you want to keep your code simple and avoid pointer complexity.
Syntax
Go
func (v Type) MethodName() {
    // method body
}

The receiver v is a copy of the original value.

Changes to v inside the method do not affect the original.

Examples
This method uses a value receiver. It changes the copy, not the original Point.
Go
type Point struct {
    X, Y int
}

func (p Point) Move() {
    p.X += 1
    p.Y += 1
}
This method just reads the value and prints it. Using a value receiver is fine here.
Go
func (p Point) Display() {
    fmt.Printf("Point is at (%d, %d)\n", p.X, p.Y)
}
Sample Program

We create a Point and call Move which uses a value receiver. The original pt does not change because Move works on a copy. Then Display shows the original coordinates.

Go
package main

import "fmt"

type Point struct {
    X, Y int
}

func (p Point) Move() {
    p.X += 1
    p.Y += 1
}

func (p Point) Display() {
    fmt.Printf("Point is at (%d, %d)\n", p.X, p.Y)
}

func main() {
    pt := Point{X: 5, Y: 10}
    pt.Move() // This changes the copy, not pt
    pt.Display() // Prints original values
}
OutputSuccess
Important Notes

Value receivers get a copy, so big structs might be slower to copy.

If you want to change the original value, use pointer receivers instead.

Methods with value receivers can be called on both values and pointers.

Summary

Value receivers use a copy of the value inside methods.

They keep the original value safe from changes.

Good for small data or read-only methods.