I'm learning Rust and have no experience with threads. I'm going through the Rustlings course and I've solved the threads1.rs exercise, but I don't understand why my Mutex struct doesn't need to be dereferenced.
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::Duration;
struct JobStatus {
jobs_completed: u32,
}
fn main() {
let status = Arc::new(Mutex::new(JobStatus { jobs_completed: 0 }));
let status_shared = Arc::clone(&status);
thread::spawn(move || {
for _ in 0..10 {
thread::sleep(Duration::from_millis(250));
let mut status_shared = status_shared.lock().unwrap();
status_shared.jobs_completed += 1; // why not *status_shared?
}
});
let mut jobs_completed: u32;
loop {
jobs_completed = status.lock().unwrap().jobs_completed;
if jobs_completed < 10 {
println!("waiting... ({} jobs done)", jobs_completed);
thread::sleep(Duration::from_millis(500));
} else {
break;
}
}
}
Based on Chapter 16.3 of The Book, I would have expected to need to assign to
*status_shared.jobs_completed
in order to get to the jobs_completed field, but that generates the error:
error[E0614]: type `u32` cannot be dereferenced
--> src/main.rs:16:13
|
16 | *status_shared.jobs_completed += 1;
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Is the difference that the book gives a pointer to a simple type and the above code gives a reference to a struct?