I'm having problems with dynamic types of send pointers in Rust. I want to convert a value of type Box<MyTrait>
to &mut MyTrait
to go to the function. For example, I tried:
use std::borrow::BorrowMut; trait MyTrait { fn say_hi(&mut self); } struct MyStruct { } impl MyTrait for MyStruct { fn say_hi(&mut self) { println!("hi"); } } fn invoke_from_ref(value: &mut MyTrait) { value.say_hi(); } fn main() { let mut boxed_trait: Box<MyTrait> = Box::new(MyStruct {}); invoke_from_ref(boxed_trait.borrow_mut()); }
This fails with the following error:
error: `boxed_trait` does not live long enough --> <anon>:22:5 | 21 | invoke_from_ref(boxed_trait.borrow_mut()); | ----------- borrow occurs here 22 | } | ^ `boxed_trait` dropped here while still borrowed | = note: values in a scope are dropped in the opposite order they are created
Oddly enough, this works for &MyTrait
, but not for &mut MyTrait
. Is there a way to make this conversion work in a mutable case?
source share