我在Rust中使用动态调度指针类型时遇到了一些问题.我想类型的值转换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());
}
Run Code Online (Sandbox Code Playgroud)
此操作失败,并显示以下错误:
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 …
Run Code Online (Sandbox Code Playgroud) &dyn T
我正在尝试从 a获取a Box<dyn T>
,如以下示例所示。但是,它无法编译。
trait MyTrait {
}
struct Foo;
impl MyTrait for Foo {}
fn main() {
let b: Box<dyn MyTrait> = Box::new(Foo);
let c: &dyn MyTrait = &b;
}
Run Code Online (Sandbox Code Playgroud)
错误信息是
error[E0277]: the trait bound `Box<dyn MyTrait>: MyTrait` is not satisfied
--> src/main.rs:10:27
|
10 | let c: &dyn MyTrait = &b;
| ^^ the trait `MyTrait` is not implemented for `Box<dyn MyTrait>`
|
= note: required for the cast to the object …
Run Code Online (Sandbox Code Playgroud) rust ×2