6. Pointer Receiver Code

Methods with pointer receivers don't require that a pointer is used to call the method. The pointer will automatically be derived from the value.

type circle struct {
	x int
	y int
    radius int
}

func (c *circle) grow() {
    c.radius *= 2
}

func main() {
    c := circle{
        x: 1,
        y: 2,
        radius: 4,
    }

    // notice c is not a pointer in the calling function
    // but the method still gains access to a pointer to c
    c.grow()
    fmt.Println(c.radius)
    // prints 8
}

Go Pointer Receiver - Automatic Conversion Notes

The Key Concept

When you have a pointer receiver method, you can call it on a regular value (not a pointer). Go automatically converts it for you.

Example Breakdown

What Go Does Automatically

You write:

Go translates to:

Both Work the Same

All three ways work!

Why This Matters

Without auto-conversion, you'd have to write:

With auto-conversion, you just write:

Complete Example

The Reverse Also Works

You can call value receiver methods on pointers:

Summary of Auto-Conversions

Method Type
Call On
What Go Does

func (c *circle)

value c

(&c).method()

func (c *circle)

pointer &c

(&c).method() (no change)

func (c circle)

value c

c.method() (no change)

func (c circle)

pointer &c

(*&c).method()

Key Takeaways

1

Pointer receiver method can be called on a value.

2

Go auto-converts c.grow() β†’ (&c).grow().

3

Makes code cleaner - don't need & everywhere.

4

Still modifies original - even though you call on value.

5

Works both ways - value receivers work on pointers too.

Bottom line: Write methods naturally with . notation. Go handles the pointer conversion automatically.

Assignment

Fix the bug in the code so that setMessage sets the message field of the given email struct, and the new value persists outside the scope of the setMessage method.

Correct approach: use a pointer receiver so the method modifies the original struct. Example fixed code:

Explanation: With a value receiver (func (e email) setMessage...), the method operates on a copy, and changes are not reflected on the caller's variable. Using a pointer receiver (func (e *email) setMessage...) ensures the original struct is modified.