How to take ownership of T from Arc?

In Rust 1.15, you can use Arc::try_unwrap and Mutex::into_inner:

use std::sync::{Arc, Mutex};

fn func() -> Result<(), String> {
    let result_my = Arc::new(Mutex::new(Ok(())));
    let result_thread = result_my.clone();

    let t = std::thread::spawn(move || {
        let mut result = result_thread.lock().unwrap();
        *result = Err("something failed".to_string());
    });

    t.join().expect("Unable to join threads");

    let lock = Arc::try_unwrap(result_my).expect("Lock still has multiple owners");
    lock.into_inner().expect("Mutex cannot be locked")
}

fn main() {
    println!("func() -> {:?}", func());
}

RwLock::into_inner also exists since Rust 1.6.

Leave a Comment