Lesson 27 of 55
9 mins readPython Mutable Structs (mutable struct)
In Plain English
When state must change over time (e.g. game entities, cumulative counters), use mutable struct to allow in-place field updates.
Deep Dive: How It Works
mutable struct Syntax: mutable struct BankAccount balance::Float64 end.
Field Reassignment: acc.balance += deposit modifies the field in place.
Trade-offs: Mutable structs are heap-allocated and tracked by the garbage collector, whereas immutable structs are usually stack-allocated.
Core Rules to Remember

In-Place Field Reassignment: Modify fields directly without creating new instances.

Use Sparingly for State: Prefer immutable structs for mathematical values; use mutable structs for stateful objects.
Live Interactive Example
Hit Run Code to see it liveMutable Struct State Management
Python 3.12
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Output Console
Click "Run Code" to view the rendered output.
How it works: Field count was modified directly in place from 100 to 101 to 151.
Your Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Micro Exercise
Implement a Score Tracker
Define `mutable struct PlayerScore name::String; score::Int end`.
Create `p = PlayerScore("Player1", 10)`.
Mutate `p.score += 25`.
Print `"Player: $(p.name), Score: $(p.score)"`.
1
2
3
4
5
6
7
8
Sandbox Output
Click "Run & Check" to test your solution.
Finished reading and practicing?
Mark this lesson as completed to update your course progress.