Convert a dash line to a mutable property reference in Rust

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?

+6
source share
1 answer

I think you are faced with a limitation of the current compiler life cycle processing. borrow_mut , being a function, imposes more stringent requirements on life than necessary.

Instead, you can take a variable borrowing in the interior of the box by first playing a field, for example:

 fn main() { let mut boxed_trait: Box<MyTrait> = Box::new(MyStruct {}); invoke_from_ref(&mut *boxed_trait); } 
+7
source

Source: https://habr.com/ru/post/1013896/


All Articles