Problem extracting value from an Option>>

⚓ Rust    📅 2026-04-01    👤 surdeus    👁️ 5      

surdeus

I found an example where it seems like something that should work in Rust simply doesn't, leading to what feels like needlessly complicated code.

Here's a playground link: Rust Playground

Here's the code:

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

trait DynThingy {
    // ... stuff ...
}

struct Foo {
    bar: Option<Arc<Mutex<dyn DynThingy>>>,
}

fn fiddle_with_thingy(_thingy: Option<&mut dyn DynThingy>) {
    // ...
}

impl Foo {
    fn fiddle_with_bar(&self) {
        let bar = self.bar.as_deref().map(|ap| ap.lock().unwrap());
        
        // NOPE, you can't do this!
        // let bar = bar.map(|mut ap| &mut *ap);
        // fiddle_with_thingy(bar);
        
        // INSTEAD, you have to do this...
        match bar {
            Some(mut bar) => fiddle_with_thingy(Some(&mut *bar)),
            None => fiddle_with_thingy(None)
        }
    }
}

The comments explain the problem. I would like to use the former code here, but the compiler fails with this error:

   Compiling playground v0.0.1 (/playground)
error[E0515]: cannot return value referencing function parameter `ap`
  --> src/lib.rs:20:36
   |
20 |         let bar = bar.map(|mut ap| &mut *ap);
   |                                    ^^^^^^--
   |                                    |     |
   |                                    |     `ap` is borrowed here
   |                                    returns a value referencing data owned by the current function

error: lifetime may not live long enough
  --> src/lib.rs:17:48
   |
16 |     fn fiddle_with_bar(&self) {
   |                        - let's call the lifetime of this reference `'1`
17 |         let bar = self.bar.as_deref().map(|ap| ap.lock().unwrap());
   |                                                ^^^^^^^^^^^^^^^^^^ returning this value requires that `'1` must outlive `'static`

For more information about this error, try `rustc --explain E0515`.
error: could not compile `playground` (lib) due to 2 previous errors

It isn't clear to me why there would be a borrow-checker error. Is there a way to use Option::map the way I intended?

6 posts - 4 participants

Read full topic

🏷️ Rust_feed