Struct Initialization
Part of the Object Oriented Programming section of Coddy's GO journey — lesson 9 of 107.
Go provides several ways to initialize structs, each useful in different situations.
Named field initialization
type Person struct {
Name string
Age int
City string
}
p1 := Person{
Name: "Alice",
Age: 25,
City: "New York",
}Positional initialization (order must match field declaration)
p2 := Person{"Bob", 30, "London"}Zero-value initialization (all fields get default values)
p3 := Person{}
// Name: "", Age: 0, City: ""
Partial initialization (unset fields get zero values)
p4 := Person{Name: "Charlie"}
// Name: "Charlie", Age: 0, City: ""
Pointer to a struct using &
p5 := &Person{
Name: "Diana",
Age: 28,
City: "Paris",
}
fmt.Println(p5.Name) // DianaUsing var then assigning fields
var p6 Person
p6.Name = "Eve"
p6.Age = 22Named field initialization is the most common and readable approach. Use & when you need a pointer to the struct.
Challenge
MediumCreate three Player objects using different initialization methods:
- player1: Named field initialization using the input values
- player2: Named field initialization with Name: "Guest", Class: "Novice", HitPoints: 50
- player3: Use
vardeclaration then assign each field individually
Cheat sheet
Go provides several ways to initialize structs:
Named field initialization (most common and readable):
p1 := Person{
Name: "Alice",
Age: 25,
City: "New York",
}Positional initialization (order must match field declaration):
p2 := Person{"Bob", 30, "London"}Zero-value initialization (all fields get default values):
p3 := Person{}
// Name: "", Age: 0, City: ""Partial initialization (unset fields get zero values):
p4 := Person{Name: "Charlie"}
// Name: "Charlie", Age: 0, City: ""Pointer to a struct using &:
p5 := &Person{
Name: "Diana",
Age: 28,
}
fmt.Println(p5.Name) // DianaUsing var then assigning fields:
var p6 Person
p6.Name = "Eve"
p6.Age = 22Try it yourself
package main
import "fmt"
func main() {
var name, class string
var hp int
fmt.Scan(&name, &class, &hp)
// TODO: Create player1 using named field initialization with the input values
// TODO: Create player2 using named field initialization:
// Name: "Guest", Class: "Novice", HitPoints: 50
// TODO: Create player3 using var declaration, then assign fields:
// Name: "Hero", Class: "Knight", HitPoints: 200
fmt.Printf("Player 1: %s (%s) - HP: %d\n", player1.Name, player1.Class, player1.HitPoints)
fmt.Printf("Player 2: %s (%s) - HP: %d\n", player2.Name, player2.Class, player2.HitPoints)
fmt.Printf("Player 3: %s (%s) - HP: %d\n", player3.Name, player3.Class, player3.HitPoints)
}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