我最近看到使用dyn关键字的代码:
fn foo(arg: &dyn Display) {}
fn bar() -> Box<dyn Display> {}
Run Code Online (Sandbox Code Playgroud)
这个语法是什么意思?
鉴于此代码:
trait Base {
fn a(&self);
fn b(&self);
fn c(&self);
fn d(&self);
}
trait Derived : Base {
fn e(&self);
fn f(&self);
fn g(&self);
}
struct S;
impl Derived for S {
fn e(&self) {}
fn f(&self) {}
fn g(&self) {}
}
impl Base for S {
fn a(&self) {}
fn b(&self) {}
fn c(&self) {}
fn d(&self) {}
}
Run Code Online (Sandbox Code Playgroud)
不幸的是,我不能投&Derived给&Base:
fn example(v: &Derived) {
v as &Base;
}
Run Code Online (Sandbox Code Playgroud)
error[E0605]: non-primitive cast: `&Derived` as `&Base`
--> …Run Code Online (Sandbox Code Playgroud) 如何获得Box<B>或&B或&Box<B>从a在此代码变量:
trait A {}
struct B;
impl A for B {}
fn main() {
let mut a: Box<dyn A> = Box::new(B);
let b = a as Box<B>;
}
Run Code Online (Sandbox Code Playgroud)
此代码返回错误:
error[E0605]: non-primitive cast: `std::boxed::Box<dyn A>` as `std::boxed::Box<B>`
--> src/main.rs:8:13
|
8 | let b = a as Box<B>;
| ^^^^^^^^^^^
|
= note: an `as` expression can only be used to convert between primitive types. Consider using the `From` trait
Run Code Online (Sandbox Code Playgroud) 我有一个集合Trait,一个迭代它并执行某些操作的函数,然后我想检查实现者类型,如果它是类型Foo然后向下转换它并调用一些Foo方法.
搜索我发现任何特征,但它只能在'static类型上实现.
为了帮助展示我想要的东西:
let vec: Vec<Box<Trait>> = //
for e in vec.iter() {
e.trait_method();
// if typeof e == Foo {
// let f = e as Foo;
// f.foo_method();
//}
}
Run Code Online (Sandbox Code Playgroud)