Structs & Pointers
Defining a struct
Section titled “Defining a struct”type User struct { Name string Email string Age int}
u := User{Name: "Ada", Email: "ada@example.com", Age: 30}Methods
Section titled “Methods”A method is a function with a receiver — the type it’s attached to:
func (u User) Greeting() string { return "Hello, " + u.Name}Value receivers vs. pointer receivers
Section titled “Value receivers vs. pointer receivers”func (u User) Greeting() stringgets a copy ofu— 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.
Pointers, briefly
Section titled “Pointers, briefly”x := 10p := &x // p is a *int, pointing to x*p = 20 // dereference to set x through pfmt.Println(x) // 20Go 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.
iota and enum-like constants
Section titled “iota and enum-like constants”Go has no native enum, but iota gets you there:
type Status int
const ( StatusPending Status = iota // 0 StatusActive // 1 StatusDone // 2)