Lesson 8: Structs¶
Big Picture¶
classDiagram
class Person {
+string Name
+int Age
+Greet() string
+Birthday()
}
class Employee {
+float64 Salary
+GiveRaise(pct float64)
}
Person <|-- Employee : embeds (composition)
note for Person "value receiver copies · pointer receiver mutates"
Go has no classes and no inheritance — structs + methods + embedding give you composition instead. Use a pointer receiver when the method should mutate the struct (or to avoid copying a big struct).
Concepts¶
Defining Structs¶
Creating Instances¶
p := Person{Name: "Alice", Age: 25}
p := Person{"Alice", 25} // Positional
p := &Person{Name: "Bob"} // Pointer
Methods¶
// Value receiver
func (p Person) Greet() string {
return "Hello, " + p.Name
}
// Pointer receiver (can modify)
func (p *Person) Birthday() {
p.Age++
}
Embedding¶
Code Walkthrough¶
Full program: code/08_structs.go.
Exercises
- Add a
FullName()method to aPersonwithFirst/Lastfields. - Embed
PersoninStudentand call a promoted method. - Write the same method with a value receiver vs pointer receiver — print the field after each call.
Check Your Understanding¶
#
Which receiver type lets a method modify the struct it's called on?
#
What does embedding Person inside Employee give you?