Skip to content

Instantly share code, notes, and snippets.

@Archina
Last active September 29, 2018 12:59
Show Gist options
  • Save Archina/4102e758d46376a73ec7be3ca96ac439 to your computer and use it in GitHub Desktop.
Save Archina/4102e758d46376a73ec7be3ca96ac439 to your computer and use it in GitHub Desktop.
Rust accessing an Option within a Arc RwLock
use std::sync::{Arc, RwLock};
use std::thread;
#[derive(Debug)]
struct Object{
name: String,
}
fn main() {
let x = Arc::new(RwLock::new(Some(Object{ name: String::from("What") })));
{
let reference = x.clone();
let thread_one = thread::spawn(move || {
reference.try_read().map(|y| {
// I originally tried to access y through &*y but it is not possible
// Moongoodboy{K} in #rust-beginners pointed out that
// &*y results in a &Option<T> while
// y.as_ref() results in a Option<&T>
y.as_ref().map(|z| {
println!("{:?}", z);
Some(())
})
});
});
thread_one.join();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment