Reputation: 5702
I wrote this example (not working):
use std::sync::Mutex;
use std::ops::Deref;
pub struct DBAndCFs {
db: i32,
cfs: Vec<i32>,
}
fn main() {
let x: Mutex<Option<DBAndCFs>> = Mutex::new(Some(DBAndCFs{ db: 0, cfs: Vec::new() } ));
let DBAndCFs { ref db, ref cfs } = x.lock().unwrap().deref();
}
I have been following the docs but I am still unable to assign the db
and cfs
fields to the variables on the left.
Upvotes: 1
Views: 751
Reputation: 70860
Mutex::lock()
returns Result<MutexGuard, PoisonError>
. The first .unwrap()
unwraps this Result
. You need another .unwrap()
to unwrap the Option
, and also .as_ref()
to not move out of it:
let DBAndCFs { ref db, ref cfs } = x.lock().unwrap().as_ref().unwrap();
You also don't need the ref
because of match ergonomics (see What does pattern-matching a non-reference against a reference do in Rust?):
let DBAndCFs { db, cfs } = x.lock().unwrap().as_ref().unwrap();
Upvotes: 4