Module 3: Structs (The Custom Record)
📚 Module 3: Structs
Course ID: GO-107
Subject: The Custom Record
In Go, we don’t have “Classes.” We have Structs. A struct allows you to group different types of data into one logical unit.
🏗️ Step 1: The Grouping
🧩 The Analogy: The ID Badge
- Imagine an ID Badge for an employee.
- It has a Name (String).
- It has an ID Number (Int).
- It has an IsAdmin status (Bool).
- The Struct is the plastic badge holder that keeps them all together.
🏗️ Step 2: In Code
// 1. Define the blueprint
type User struct {
Name string
Age int
Admin bool
}
// 2. Create a real user
alice := User{
Name: "Alice",
Age: 25,
Admin: true,
}
// 3. Access a field
fmt.Println(alice.Name)🏗️ Step 3: Methods (The “Skillset”)
In other languages, methods live “inside” the class. In Go, we use a Receiver to attach a function to a struct.
func (u User) Greet() {
fmt.Println("Hello, my name is", u.Name)
}
// Now you can call:
alice.Greet()🥅 Module 3 Review
- Struct: A collection of fields.
- Fields: The data stored inside the struct.
- Receiver: How we attach “Skills” (Methods) to a struct.
:::tip Slow Learner Note Structs are much simpler than Classes. They are just containers for data. If you want to change the data inside, you’ll need Pointers (Module 4)! :::