簡體   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