Go - Structs

Beginner 10/10 Teacher 10/10 Architect 10/10
Try it: Define a Book struct with Title and Author, then print a value with fmt.Printf("%+v", b).

Basics

type User struct{ ID int; Name string }
u := User{ID:1, Name:"Alice"}

Embedding

type Timestamps struct{ CreatedAt time.Time }
type Customer struct{
  Timestamps
  ID int
}

Tags

type Product struct{
  Name string `json:"name"`
}

Common errors

  • Forgetting field names in composite literals when order changes—prefer keyed fields.
  • Exporting fields: only capitalized field names are exported for JSON and other packages.

Practice

  • Add JSON tags to your Book struct and serialize it.

Quick quiz

  1. What’s struct embedding and why use it?
Show answer Embedding includes fields/methods of another struct for composition and code reuse.