繁体   English   中英

Rust:作为返回类型的特征

[英]Rust: Trait as a return type

假设有这样的代码:

trait A {
  fn something(&self) -> String
}

struct B {
  things: Vec<u64>
}

struct C {
  thing: Box<&dyn A>
}

impl A for B { ... }

fn create_thing() -> B {
  // 
}

impl C {
  pub fn new() {
    let thing = create_thing();
    C { thing }
  }
}

我的问题是与Box<&dyn A>匹配的create_thing的返回类型究竟应该是什么,或者返回值应该如何包装以与Box<&dyn A>匹配?

等效的 C# 代码如下所示:

interface A {}
class B : A {}
class C {
  public A field;
  public C() {
    this.field = new B();
  }
}

在下面找到您的代码,稍作调整即可编译。

我怀疑Box<&dyn A>不是故意的,因为它意味着引用本身是堆分配的(而不是被引用的对象)。 另一方面, Box<dyn A>与您的 C# 示例相匹配。

返回类型create_thing()对我来说看起来不错,因为它不为返回值假定任何特定类型的存储(堆栈、堆、向量内...)。 您只需要Box这个结果值,以便在初始化C时提供它。

但是,如果您想隐藏create_thing()确切返回类型为B的事实,您可以像这样更改fn create_thing() -> impl A

如果你真的想返回一个 dyn trait 对象,那么将它更改为fn create_thing() -> Box<dyn A>并在此处而不是在C::new()创建框。

trait A {
    fn something(&self) -> String;
}

struct B {
    things: Vec<u64>,
}

struct C {
    thing: Box<dyn A>,
}

impl A for B {
    fn something(&self) -> String {
        format!("something on B with {:?}", self.things)
    }
}

fn create_thing() -> B {
    B {
        things: vec![1, 2, 3],
    }
}

impl C {
    pub fn new() -> Self {
        let thing = Box::new(create_thing());
        Self { thing }
    }
}

fn main() {
    let c = C::new();
    println!("{}", c.thing.something());
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM