Last active
September 29, 2018 12:59
-
-
Save Archina/4102e758d46376a73ec7be3ca96ac439 to your computer and use it in GitHub Desktop.
Rust accessing an Option within a Arc RwLock
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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