重构我的代码以在Rust中实现合成的最佳方法是什么?

时间:2018-12-20 05:40:02

标签: design-patterns rust composition

下面有很多重复的代码。重构的最佳方法是什么?

我来自JavaScript,在其中我使用合成来达到相同的结果,但是在Rust中,我似乎必须重新实现许多代码。

我知道有一种使用宏的方法,但是如果逻辑更复杂,由于宏是内联的,我将得到一个很大的可执行文件。

struct Shape {
    x: i32,
    y: i32,
}

struct Circle {
    x: i32,
    y: i32,
    radious: i32,
}

struct Square {
    x: i32,
    y: i32,
    width: i32,
    height: i32,
}

trait Advance {
    fn advance(&mut self);
}

impl Advance for Shape {
    fn advance(&mut self) {
        self.x += 1;
    }
}

impl Advance for Square {
    fn advance(&mut self) {
        self.x += 1;
    }
}

impl Advance for Circle {
    fn advance(&mut self) {
        self.x += 1;
    }
}

fn main() {
    println!("Hello World!!");

    let mut shape = Shape { x: 0, y: 0 };
    let mut square = Square {
        x: 0,
        y: 0,
        width: 10,
        height: 10,
    };
    let mut circle = Circle {
        x: 0,
        y: 0,
        radious: 5,
    };

    while shape.x < 10 {
        shape.advance();
        circle.advance();
        square.advance();
        println!("shape {}", shape.x);
        println!("circle {}", circle.x);
        println!("square {}", square.x);
        println!("---------------------");
    }
}

playground

1 个答案:

答案 0 :(得分:1)

无法扩展结构,但是您可以将公共属性放入另一个结构中,并且您的结构可以由这些公共结构组成。可以通过Point之类的常见结构来触发常见行为。

#[derive(Default)]
struct Point {
    x: i32,
    y: i32,
}

struct Shape {
    point: Point,
}

struct Circle {
    point: Point,
    radious: i32,
}

struct Square {
    point: Point,
    width: i32,
    height: i32,
}

trait Advance {
    fn advance(&mut self);
}

impl Advance for Point {
    fn advance(&mut self) {
        self.x += 1;
    }
}

fn main() {
    let mut shape = Shape {
        point: Point::default(),
    };
    let mut square = Square {
        point: Point::default(),
        width: 10,
        height: 10,
    };
    let mut circle = Circle {
        point: Point::default(),
        radious: 5,
    };

    while shape.point.x < 10 {
        shape.point.advance();
        circle.point.advance();
        square.point.advance();
        println!("shape {}", shape.point.x);
        println!("circle {}", circle.point.x);
        println!("square {}", square.point.x);
        println!("---------------------");
    }
}

Playground