6
可變特性引用我遇到一些麻煩魯斯特動態分配指針類型。我想將Box<MyTrait>
類型的值轉換爲&mut MyTrait
以傳遞給函數。例如,我想:轉換盒裝性狀魯斯特
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());
}
這失敗,出現以下錯誤:
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
奇怪的是,這個工程的&MyTrait
而不是&mut MyTrait
。有什麼辦法可以讓這個轉換工作在可變的情況下?