Skip to content

Structs & Pointers

type User struct {
Name string
Email string
Age int
}
u := User{Name: "Ada", Email: "ada@example.com", Age: 30}

A method is a function with a receiver — the type it’s attached to:

func (u User) Greeting() string {
return "Hello, " + u.Name
}
  • func (u User) Greeting() string gets a copy of u — fine for read-only methods.
  • func (u *User) Birthday() gets a pointer to the original — required whenever a method needs to mutate the receiver.

As a rule of thumb: if any method on a type needs a pointer receiver, make all of that type’s methods pointer receivers for consistency.

x := 10
p := &x // p is a *int, pointing to x
*p = 20 // dereference to set x through p
fmt.Println(x) // 20

Go has pointers but no pointer arithmetic — you can point to a value and dereference it, but you can’t do p + 1 like in C. This keeps memory safety intact while still letting you avoid copying large structs.

Go has no native enum, but iota gets you there:

type Status int
const (
StatusPending Status = iota // 0
StatusActive // 1
StatusDone // 2
)