6
Rustのダイナミックディスパッチポインタ型に問題があります。私はタイプBox<MyTrait>
の値を&mut MyTrait
に変換して関数に渡したいと思います。例えば、私が試した:Rustのboxable traitをmutable trait referenceに変換する
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
のために動作します。変更可能な場合にこの変換を実行する方法はありますか?