Lesson 5 / 7

Pointers and Methods

Pointers, simplified

score := 90nscorePtr := &score      // scorePtr holds the memory address of scorenfmt.Println(*scorePtr)   // dereference: 90n*scorePtr = 95nfmt.Println(score)       // 95 -- changed through the pointer

Go has pointers, using the same & (address-of) and * (dereference) syntax as C++, covered in that course’s functions and pointers lesson. Go’s version is deliberately simpler, though — there is no pointer arithmetic, and Go’s garbage collector manages memory automatically, so you never call anything like C++’s delete.

Methods on structs

type Course struct {n    Title       stringn    LessonCount intn}nnfunc (c Course) Describe() string {n    return fmt.Sprintf("%s has %d lessons", c.Title, c.LessonCount)n}nngoCourse := Course{Title: "Go", LessonCount: 7}nfmt.Println(goCourse.Describe())

(c Course) before the function name is called a receiver — it attaches Describe to the Course type, letting you call it as goCourse.Describe(). This is how Go attaches behavior to data without a class keyword at all.

Pointer receivers — for methods that modify the struct

func (c *Course) Rename(newTitle string) {n    c.Title = newTitlen}nngoCourse.Rename("Go Programming")nfmt.Println(goCourse.Title)   // Go Programming

A regular (value) receiver like Describe above operates on a copy of the struct — changes inside it never affect the original. A pointer receiver, (c *Course), operates on the original struct directly, exactly like the & reference parameters from the C++ course. Any method that needs to modify the struct must use a pointer receiver.

Interfaces

type Describable interface {n    Describe() stringn}nnfunc printDescription(d Describable) {n    fmt.Println(d.Describe())n}

Go interfaces are satisfied implicitly — Course automatically satisfies Describable simply by having a matching Describe() string method, with no implements keyword required anywhere. This is structurally similar to TypeScript’s interfaces, and different from Java’s explicit implements declaration.