Start learning free

LESSON 401 OF 414 · OBJECT-ORIENTED PROGRAMMING

Static Members in Rust in Rust

Practice

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

    Static Members in Rust

    Keep going with RustAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free