Zero Values & Defaults
Part of the Object Oriented Programming section of Coddy's GO journey — lesson 17 of 107.
In Go, every variable has a zero value — the default value assigned when you declare a variable without explicit initialization. Understanding zero values is essential for working with structs, as uninitialized fields automatically receive these defaults.
Each type has its own zero value:
| Type | Zero Value |
|---|---|
| int, float64 | 0 |
| string | "" (empty string) |
| bool | false |
| pointer, slice, map | nil |
When you create a struct, any field you don't explicitly set gets its zero value.
type User struct {
Name string
Age int
Active bool
}
func main() {
var u User
fmt.Println(u.Name) // "" (empty string)
fmt.Println(u.Age) // 0
fmt.Println(u.Active) // false
}This also applies to partial initialization. Only the fields you specify get custom values.
u := User{Name: "Alice"}
fmt.Println(u.Age) // 0
fmt.Println(u.Active) // false
Zero values make structs immediately usable without explicit initialization. However, be careful with reference types like slices and maps — their zero value is nil, which can cause runtime panics if you try to use them without initialization.
Challenge
EasyLet's build a player profile system that demonstrates how zero values work in Go. You'll create a game profile where some fields are explicitly set while others rely on their default zero values.
You'll organize your code across two files:
player.go: Define aPlayerstruct with the following fields:Username(string),Level(int),Score(int),IsPremium(bool), andGuildName(string). Also create aDisplayProfilemethod that returns a formatted string showing all the player's information.main.go: Read a username from input and create a Player using only partial initialization—set just theUsernamefield. Then display the complete profile to see how Go fills in the unset fields with their zero values.
The following input will be provided:
- Line 1: The player's username
Your DisplayProfile method should return a string in this exact format:
Username: [Username]
Level: [Level]
Score: [Score]
Premium: [IsPremium]
Guild: [GuildName]For example, if the username is ShadowKnight, your output should show the username along with all the zero values for the uninitialized fields:
Username: ShadowKnight
Level: 0
Score: 0
Premium: false
Guild: Notice how the Guild field shows nothing after the colon—that's the empty string zero value. This challenge helps you see exactly what Go assigns to each type when you don't provide an explicit value.
Cheat sheet
In Go, every variable has a zero value — the default value assigned when you declare a variable without explicit initialization.
Each type has its own zero value:
| Type | Zero Value |
|---|---|
| int, float64 | 0 |
| string | "" (empty string) |
| bool | false |
| pointer, slice, map | nil |
When you create a struct, any field you don't explicitly set gets its zero value:
type User struct {
Name string
Age int
Active bool
}
func main() {
var u User
fmt.Println(u.Name) // "" (empty string)
fmt.Println(u.Age) // 0
fmt.Println(u.Active) // false
}Partial initialization — only specified fields get custom values:
u := User{Name: "Alice"}
fmt.Println(u.Age) // 0
fmt.Println(u.Active) // falseZero values make structs immediately usable without explicit initialization. Be careful with reference types like slices and maps — their zero value is nil, which can cause runtime panics if used without initialization.
Try it yourself
package main
import (
"fmt"
)
func main() {
// Read the username from input
var username string
fmt.Scanln(&username)
// TODO: Create a Player using partial initialization
// Only set the Username field, let other fields use zero values
// TODO: Display the player's profile using the DisplayProfile method
}
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