Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

A value receiver method in Go is a function bound to a specific type where the receiver argument is passed by value. When invoked, the method operates on a distinct, shallow copy of the original instance, ensuring that any state mutations within the method’s scope do not affect the caller’s original data.

Syntax

The receiver is declared between the func keyword and the method name. It consists of an identifier and the base type (not a pointer).
func (v Type) MethodName(parameterList) returnType {
    // v is a localized copy of the caller's value
}

Technical Mechanics

Pass-by-Value Semantics When a value receiver method is called, Go allocates new memory for the receiver and copies the data from the caller into this new memory space. Because it operates on a copy, any modifications made to the receiver’s fields inside the method are discarded once the method returns. Automatic Dereferencing Go provides syntactic sugar for method invocations. You can call a value receiver method on a pointer to the type. The Go compiler automatically dereferences the pointer (*p) to extract the value before passing the copy to the method. Method Sets and Interfaces In Go’s type system, the method set of a type determines which interfaces that type implements. A method with a value receiver (t T) is automatically included in the method set of both the value type T and the pointer type *T. Consequently, both T and *T can satisfy an interface that requires a value receiver method.

Code Visualization

The following example demonstrates the isolation of mutations and automatic pointer dereferencing inherent to value receivers:
package main

import "fmt"

type Vector struct {
    X, Y int
}

// Translate is a value receiver method.
// 'v' is a copy of the Vector used to invoke the method.
func (v Vector) Translate(dx, dy int) {
    v.X += dx
    v.Y += dy
    fmt.Printf("Inside method: %+v\n", v)
}

func main() {
    // 1. Invoking on a value
    val := Vector{X: 0, Y: 0}
    val.Translate(5, 5)
    // val remains {X: 0, Y: 0} because Translate mutated a copy
    fmt.Printf("After value call: %+v\n", val)

    // 2. Invoking on a pointer
    ptr := &Vector{X: 0, Y: 0}
    ptr.Translate(5, 5) // Compiler translates this to: (*ptr).Translate(5, 5)
    // ptr remains &{X: 0, Y: 0}
    fmt.Printf("After pointer call: %+v\n", ptr)
}
Master Go with Deep Grasping Methodology!Learn More