Structs as Classes
Part of the Object Oriented Programming section of Coddy's GO journey — lesson 6 of 107.
Structs in Go serve the same purpose as classes in other languages. They bundle related data together into a single type.
Define a struct with multiple field types
type Car struct {
Brand string
Model string
Year int
Price float64
}Create an instance using field names
car := Car{
Brand: "Toyota",
Model: "Camry",
Year: 2023,
Price: 28000.50,
}Access and modify fields
fmt.Println(car.Brand) // Toyota
fmt.Println(car.Year) // 2023
car.Price = 27000.00 // Modify a field
fmt.Println(car.Price) // 27000Structs can contain other structs
type Engine struct {
Horsepower int
FuelType string
}
type Car struct {
Brand string
Model string
Engine Engine
}
car := Car{
Brand: "Ford",
Model: "Mustang",
Engine: Engine{Horsepower: 450, FuelType: "Gasoline"},
}
fmt.Println(car.Engine.Horsepower) // 450Structs group related fields together. You access fields with the dot operator, and you can nest structs inside other structs to build complex data models.
Challenge
MediumDefine a Profile struct with the following fields:
Name— stringEmail— stringAge— intRole— string
Cheat sheet
Structs in Go bundle related data together into a single type, similar to classes in other languages.
Define a struct with multiple field types:
type Car struct {
Brand string
Model string
Year int
Price float64
}Create an instance using field names:
car := Car{
Brand: "Toyota",
Model: "Camry",
Year: 2023,
Price: 28000.50,
}Access and modify fields using the dot operator:
fmt.Println(car.Brand) // Toyota
car.Price = 27000.00 // Modify a fieldStructs can contain other structs (nested structs):
type Engine struct {
Horsepower int
FuelType string
}
type Car struct {
Brand string
Model string
Engine Engine
}
car := Car{
Brand: "Ford",
Model: "Mustang",
Engine: Engine{Horsepower: 450, FuelType: "Gasoline"},
}
fmt.Println(car.Engine.Horsepower) // 450Try it yourself
package main
import "fmt"
func main() {
var name, email, role string
var age int
fmt.Scan(&name, &email, &age, &role)
p := Profile{
Name: name,
Email: email,
Age: age,
Role: role,
}
fmt.Printf("Name: %s\n", p.Name)
fmt.Printf("Email: %s\n", p.Email)
fmt.Printf("Age: %d\n", p.Age)
fmt.Printf("Role: %s\n", p.Role)
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of Go OOP
External FilesGo Workspace & ModulesPackages & ImportsExported vs Unexported NamesIntroduction to OOP in GoStructs as ClassesDefining Methods on StructsPointer vs Value ReceiversStruct InitializationConstructor FunctionsRecap - Simple Calculator4Interfaces
Introduction to InterfacesImplicit ImplementationInterface as ContractEmpty Interface (any)Type AssertionType SwitchInterface CompositionStringer & Error InterfacesRecap - Shape Calculator7Encapsulation
Exported vs Unexported FieldsPackage-Level EncapsulationGetter & Setter MethodsInformation Hiding in GoRecap - Student Records10Generics (Go 1.18+)
Introduction to GenericsType ParametersType ConstraintsGeneric StructsGeneric Methods WorkaroundRecap - Generic Collection2Types & Structs Deep Dive
Basic & Composite TypesCustom Type DefinitionsStruct TagsAnonymous StructsNested StructsZero Values & DefaultsRecap - Contact Book5Composition Over Inheritance
Why Go Has No InheritanceStruct Embedding BasicsMethod PromotionEmbedding Multiple StructsEmbedding vs AggregationShadowing Embedded MethodsRecap - Employee Hierarchy8Error Handling & OOP
The error InterfaceCustom Error TypesError Wrapping (fmt.Errorf)Sentinel Errorserrors.Is() and errors.As()Panic, Defer, and RecoverRecap - File Parser3Pointers & Memory
Pointer Basics in GoPointers to StructsPass by Value vs ReferenceThe new() FunctionGarbage Collection in GoRecap - Linked List Builder6Polymorphism in Go
Polymorphism via InterfacesDuck Typing in GoInterface Satisfaction RulesPolymorphic CollectionsDependency InjectionRecap - Payment Processor9Concurrency & OOP
Goroutines BasicsChannels & CommunicationBuffered vs Unbuffered ChanSelect Statementsync.Mutex & sync.RWMutexsync.WaitGroupThread-Safe Struct DesignRecap - Worker Pool