Start learning free

LESSON 29 OF 69 · OBJECT-ORIENTED PROGRAMMING

Static Members in Rust: A Shared Counter with static mut

Practice Read the full explanation

TL;DR:

Rust structs have no static fields. A shared counter is a module-level static mut variable, and since changing it is unsafe (two threads could race), every read and write sits inside an unsafe block. The impl block's new function plays the role of the constructor.

You start with:

struct Dog {
    name: String,
}

Your task: count how many Dog objects have been created, with one counter shared by all of them.

  • Declare static mut COUNT: i32 = 0; at module level, then open impl Dog with fn new(name: &str) -> Dog.
  • Inside new, do unsafe { COUNT += 1; }, then return Dog { name: name.to_string() }.
  • The counter starts at 0 before any dog exists, and goes up by exactly 1 for every dog created, whatever its name.
  • The program that is already in the editor creates Rex and Buddy and prints the counter; then it creates Max, prints the counter and Max's name, creates Luna, and prints the counter once more. Do not change those lines.

Expected output:

2
3
Max
4

Read the counter inside an unsafe block.

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);
    }
}

STEP 1 OF 7
    Ctrl + Enter to check

    RUST · OBJECT-ORIENTED PROGRAMMING

    Static Members in Rust, explained

    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 static item at module level. A static exists once for the whole program, which is the "one copy shared by everyone" the counter needs. Adding mut makes it changeable.
    • An associated function in an impl Dog block. A function there without a self parameter is called through the type, as Dog::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

    1. Define the struct. Dog has one field, name, a String. The struct holds each dog's own data and nothing shared.
    2. 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.
    3. Open impl Dog, the block that holds the functions belonging to the type.
    4. Write the signature of new: it takes name: &str and returns a Dog.
    5. Open an unsafe block in new, because changing a static mut requires one.
    6. Add 1 to COUNT inside it. This line runs for every dog, so the counter grows by one per call.
    7. Return the new Dog after the block. The field's value, name.to_string(), turns the borrowed &str into an owned String. 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. Writing COUNT += 1; outside an unsafe block fails with error[E0133]: use of mutable static is unsafe and requires unsafe function or block. The printing in mainFunction needs unsafe as 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) triggers warning: creating a shared reference to mutable static. The macro takes a reference to its argument, and references to static mut are 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. rex and buddy are never read, so the compiler warns about them. The warning is harmless and the dogs still count.
    • Function naming. mainFunction isn't snake_case, so rustc adds a naming warning. It doesn't affect the result.
    • Safe alternative. A shared counter without unsafe can use an atomic: static COUNT: AtomicI32 = AtomicI32::new(0); from std::sync::atomic, changed with COUNT.fetch_add(1, Ordering::SeqCst) and read with COUNT.load(Ordering::SeqCst). It is safe even across threads. The lesson uses static mut to 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 count inside Dog would 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 in mainFunction would 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 plain static COUNT: i32 can't be modified at all.
    • Using a &str field. The struct stores a String, so new converts with to_string(). Storing the borrowed &str would need a lifetime on the struct.

    Key takeaways

    • Rust has no static fields. Shared state lives in a module-level static.
    • A static mut must be read and written inside unsafe, because the compiler can't rule out a data race.
    • An associated function without self, called as Dog::new(...), is Rust's usual constructor.
    • For a shared counter that needs no unsafe, use an atomic type.
    Keep going with Rust1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free