Note: This site is currently "Under construction". I'm migrating to a new version of my site building software. Lots of things are in a state of disrepair as a result (for example, footnote links aren't working). It's all part of the process of building in public. Most things should still be readable though.

Use And Change Mutex Value In A Rust Struct Object

Code

use std::sync::Mutex;

#[derive(Debug)]
pub struct Widget {
    pub holder: Mutex<u8>,
}

impl Widget {
    pub fn new(holder: Mutex<u8>) -> Widget {
        Widget { holder }
    }
    pub fn move_it(&self) {
        let mut pinger = self.holder.lock().unwrap();
        *pinger = 7;
    }
}

fn main() {
    let holder = Mutex::new(5);
    let w = Widget { holder };
    println!("m = {:?}", w.holder);
    w.move_it();
    println!("m = {:?}", w.holder);
}

Results

m = Mutex { data: 5, poisoned: false, .. }
m = Mutex { data: 7, poisoned: false, .. }