私信  •  关注

Nathan Ringo

Nathan Ringo 最近创建的主题
Nathan Ringo 最近回复了
7 年前
回复了 Nathan Ringo 创建的主题 » 如何在RIST中重新实现jQuery样式链接?[副本]

我已经看到构建器模式主要是通过在修改时获得构建器的所有权来实现的,并且通过引用 build() 是的。例如,

#[derive(Debug, Eq, PartialEq)]
struct Foo {
    value: usize,
}

struct FooBuilder {
    foos: usize,
    bars: usize,
}

impl FooBuilder {
    fn new() -> FooBuilder {
        FooBuilder {
            foos: 0,
            bars: 0,
        }
    }
    fn set_foos(mut self, foos: usize) -> FooBuilder {
        self.foos = foos;
        self
    }
    fn set_bars(mut self, bars: usize) -> FooBuilder {
        self.bars = bars;
        self
    }
    fn build(&self) -> Foo {
        Foo {
            value: self.foos + self.bars,
        }
    }
}

fn main() {
    let foo = FooBuilder::new()
        .set_foos(2)
        .set_bars(3)
        .build();
    assert_eq!(foo, Foo { value: 5 });
}

Try on Rust Playground

这使得链接简单,同时允许重用生成器。