相关疑难解决方法(0)

"dyn"在一个类型中意味着什么?

我最近看到使用dyn关键字的代码:

fn foo(arg: &dyn Display) {}

fn bar() -> Box<dyn Display> {}
Run Code Online (Sandbox Code Playgroud)

这个语法是什么意思?

syntax rust

41
推荐指数
3
解决办法
2788
查看次数

为什么Rust不支持特征对象向上转换?

鉴于此代码:

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)

oop language-design liskov-substitution-principle rust

40
推荐指数
4
解决办法
6616
查看次数

如何从特征对象获取对具体类型的引用?

如何获得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)

traits rust

38
推荐指数
2
解决办法
9184
查看次数

我可以用特征对象键入内省然后向下转换吗?

我有一个集合Trait,一个迭代它并执行某些操作的函数,然后我想检查实现者类型,如果它是类型Foo然后向下转换它并调用一些Foo方法.

基本上,类似于Go的类型切换界面转换.

搜索我发现任何特征,但它只能在'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)

rust

10
推荐指数
1
解决办法
2303
查看次数