gpt4 book ai didi

rust - 如何在 Rust 中实现抽象工厂?

转载 作者:行者123 更新时间:2023-12-03 11:25:23 25 4
gpt4 key购买 nike

就像是:

trait Thingy {
fn hallo(&self);
}

trait Factory {
fn make(&self) -> Thingy;
}
//------------------------------
struct AThingy {}

impl Thingy for AThingy {
fn hallo(&self) {
println!("i'm A thingy");
}
}

struct AFactory {}

impl Factory for AFactory {
fn make(&self) -> AThingy {
AThingy{}
}
}

//------------------------------
struct BThingy {}

impl Thingy for BThingy {
fn hallo(&self) {
println!("i'm B thingy");
}
}

struct BFactory {}

impl Factory for BFactory {
fn make(&self) -> BThingy {
BThingy{}
}
}

//------------------------------
#[test]
fn test_factory() {
let aFactory:Factory = AFactory{};
let bFactory:Factory = BFactory{};

aFactory.make().hallo();
bFactory.make().hallo();
}
试图在不同的地方附加 Sized 但都失败了。

最佳答案

您可以使用关联类型。 Factory可以有一个名为 Output 的关联类型.您可以添加需要 Output 的边界。实现 Thingy :

trait Factory {
type Output: Thingy;

fn make(&self) -> Self::Output;
}
现在, AFactoryOutput将是 AThingy :
impl Factory for AFactory {
type Output = AThingy;

fn make(&self) -> AThingy {
AThingy {}
}
}
BFactoryOutput将是 BThingy :
impl Factory for BFactory {
type Output = BThingy;

fn make(&self) -> BThingy {
BThingy {}
}
}
正如@PeterHall 提到的,您无法在 Rust 中处理未定义大小的类型,因此要存储 Factory你需要使用像 Box<dyn Factory> 这样的自有指针:
#[test]
fn test_factory() {
let aFactory: Box<dyn Factory> = Box::new(AFactory {});
let bFactory: Box<dyn Factory> = Box::new(BFactory {});

aFactory.make().hallo();
bFactory.make().hallo();
}
然而,因为 Factory具有关联类型,您还必须指定 Output当把它变成一个 trait 对象时:
#[test]
fn test_factory() {
let aFactory: Box<dyn Factory<Output = AThingy>> = AFactory {};
let bFactory: Box<dyn Factory<Output = BThingy>> = BFactory {};

aFactory.make().hallo();
bFactory.make().hallo();
}

关于rust - 如何在 Rust 中实现抽象工厂?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65847670/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com