Problem overview
In many languages a class can have a static field, one value shared by every object of that class. A common use is counting how many objects have been created. This lesson builds that for a Dog struct: every call to Dog::new adds one to a shared counter, whatever the dog's name.
The program already in the editor creates Rex and Buddy and prints the counter, creates Max and prints the counter and his name, then creates Luna and prints the counter once more. The expected output is:
2
3
Max
4
The counter is 0 before any dog exists and rises by exactly one per dog, so the four dogs produce 2, 3 and 4 at the three printing points.
Approach: a module-level static, a constructor in impl
Rust structs can't have static fields. The language keeps data that belongs to the type itself out of the struct, so two pieces are needed:
- A
staticitem at module level. A static exists once for the whole program, which is the "one copy shared by everyone" the counter needs. Addingmutmakes it changeable. - An associated function in an
impl Dogblock. A function there without aselfparameter is called through the type, asDog::new("Rex"). It plays the role of a constructor, and it is the one place where the counter has to change.
Rust treats a mutable static as dangerous. If two threads changed it at once, the result would be a data race, and the compiler can't prove that won't happen. Every read or write of a static mut therefore sits inside an unsafe block. The block doesn't switch off checking in general. It is a promise from you that the access is fine, here because this program is single-threaded.
Step by step
- Define the struct.
Doghas one field,name, aString. The struct holds each dog's own data and nothing shared. - Declare the counter below it:
static mut COUNT: i32 = 0;. A static must have an explicit type and a value that is known when the program is built. Constants and statics are conventionally written in capitals. - Open
impl Dog, the block that holds the functions belonging to the type. - Write the signature of
new: it takesname: &strand returns aDog. - Open an
unsafeblock innew, because changing astatic mutrequires one. - Add 1 to
COUNTinside it. This line runs for every dog, so the counter grows by one per call. - Return the new
Dogafter the block. The field's value,name.to_string(), turns the borrowed&strinto an ownedString. The expression has no semicolon, so it is the return value.
The solution in Rust
struct Dog {
name: String,
}
static mut COUNT: i32 = 0;
impl Dog {
fn new(name: &str) -> Dog {
unsafe {
COUNT += 1;
}
Dog {
name: name.to_string(),
}
}
}
fn mainFunction() {
let rex = Dog::new("Rex");
let buddy = Dog::new("Buddy");
unsafe {
println!("{}", COUNT);
}
let third = Dog::new("Max");
unsafe {
println!("{}", COUNT);
}
println!("{}", third.name);
Dog::new("Luna");
unsafe {
println!("{}", COUNT);
}
}
Details worth knowing:
- The compiler enforces
unsafe. WritingCOUNT += 1;outside anunsafeblock fails witherror[E0133]: use of mutable static is unsafe and requires unsafe function or block. The printing inmainFunctionneedsunsafeas well, since reading is also an access. - A warning on the print lines. With Rust 1.94 in edition 2021, the program compiles and prints the expected output, but
println!("{}", COUNT)triggerswarning: creating a shared reference to mutable static. The macro takes a reference to its argument, and references tostatic mutare discouraged because they can alias a later change. In the 2024 edition that lint is stricter. The lesson's code runs as written; in new code, prefer the alternative below. - Ignoring the result of
new.Dog::new("Luna");builds a dog and drops it at once, yet the counter still goes up, because the increment happens during construction. The count measures how many were created, not how many are alive. - Unused variables.
rexandbuddyare never read, so the compiler warns about them. The warning is harmless and the dogs still count. - Function naming.
mainFunctionisn't snake_case, so rustc adds a naming warning. It doesn't affect the result. - Safe alternative. A shared counter without
unsafecan use an atomic:static COUNT: AtomicI32 = AtomicI32::new(0);fromstd::sync::atomic, changed withCOUNT.fetch_add(1, Ordering::SeqCst)and read withCOUNT.load(Ordering::SeqCst). It is safe even across threads. The lesson usesstatic mutto show the closest match to a static field and why Rust makes you mark it.
Edge cases and common mistakes
- Putting the counter in the struct. A field like
countinsideDogwould belong to one dog, so every dog would start at its own zero. - Counting in the wrong place. The increment must be in
new, the only function that creates dogs. Incrementing inmainFunctionwould count once per call site and miss dogs created elsewhere. - Starting at the wrong value. The counter starts at 0, so after Rex and Buddy it reads 2, not 3.
- Forgetting
mut. A plainstatic COUNT: i32can't be modified at all. - Using a
&strfield. The struct stores aString, sonewconverts withto_string(). Storing the borrowed&strwould need a lifetime on the struct.
Key takeaways
- Rust has no static fields. Shared state lives in a module-level
static. - A
static mutmust be read and written insideunsafe, because the compiler can't rule out a data race. - An associated function without
self, called asDog::new(...), is Rust's usual constructor. - For a shared counter that needs no
unsafe, use an atomic type.
