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 openimpl Dogwithfn new(name: &str) -> Dog. - Inside
new, dounsafe { COUNT += 1; }, then returnDog { 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
RexandBuddyand prints the counter; then it createsMax, prints the counter and Max's name, createsLuna, 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);
}
}
Free plan: 30 tutor messages. Premium is unlimited.
Saved
Ctrl + Enter to check
