1

The Rust documentation has a OnceLock::get_mut method that returns a mutable reference. But the following code does not compile. What am I missing?

use std::sync::OnceLock;
#[derive(Clone)]
struct System {
    comp: Vec<i32>,
}

static GLOB: OnceLock<System> = OnceLock::new();

impl System {
    fn new() -> Self {
        Self { comp: Vec::new() }
    }
}
fn modify(global: &mut System) {
    global.comp.push(42);
}

fn main() {
    let sys: Box<System> = Box::new(System::new());
    GLOB.get_or_init(|| *sys);
    let global: &mut System = GLOB.get_mut().unwrap();
    println!("global size is {}", global.comp.len());
    modify(global);
    println!("global size is {}", global.comp.len());
}

Is it really possible to get a mutable reference? How am I supposed to use get_mut()?

1 Answer 1

3

You can't get a mutable reference to any binding that's not marked as mutable, that includes statics, though a static mut is discouraged and very likely not what you want. But you don't have to use OnceLock with statics:

let mut glob: OnceLock<System> = OnceLock::new();
let global: &mut System = glob.get_mut().unwrap();

Though if you need mutable access after initialization you should use a Mutex or RwLock instead.

Sign up to request clarification or add additional context in comments.

3 Comments

At this point, why use OnceLock?
@ChayimFriedman I would imagine it's useful in similar situations where Mutex::get_mut is. There might be part of the program that only has a shared reference, but another part might have exclusive access and may want to mutate the inner value. Honestly I don't have a concrete usecase, but I can imagine someone might have one.
Exactly. I have a data model and there is one single thread that can modify the model. All of the other threads must act accordingly. I guess I will use RwLock...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.