4 ms·
People always complain about unsafe, so I prefer to just show the safe version. use std::sync::Mutex; static LIST: Mutex<Vec<String>> = Mutex::new(Vec::ne
by raggi 10mo ago
People always complain about unsafe, so I prefer to just show the safe version.
use std::sync::Mutex;
static LIST: Mutex<Vec<String>> = Mutex::new(Vec::new());
fn main() -> Result<(), Box<dyn std::error::Error>> {
LIST.lock()?.push("hello world".to_string());
println!("{}", LIST.lock()?[0]);
Ok(())
}
- hu3 10mo agoThis is completely different from the previous example. It doesn't increment anything for starters. The example would be more convoluted if it did the same thing. And strings in rust always delivers the WTFs I need o na Friday: "hello world".to_string()
- raggi 10mo agouse std::sync::Mutex; fn main() -> Result<(), Box<dyn std::error::Error>> { static PEDANTRY: Mutex<u64> = Mutex::new(0); *PEDANTRY.lock()? += 1; println!("{}", PEDANTRY.lock()?); Ok(()) }
- hu3 10mo agoStill different. Yours only increments once. Doesn't pass basic QA. And declaring a static variable inside a function, even if in main, smells.
- raggi 10mo agoOP you keep comparing to doesn't even declare the variable. I'm done with you.
- School-Cotton 10mo agoOP here, not showing how to declare the variable was an oversight on my part. static mut COUNTER: u32 = 0; (at top-level) If on 2024 edition, you will additionally need #![allow(static_mut_refs)]
- raggi 10mo agoYup, your example was fine, as I said I just wanted to show a safe method too :-)