设计模式 – 重构我的代码以在Rust中实现组合的最佳方法是什么?

以下有很多重复的代码.重构它的最佳方法是什么?

我来自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

最佳答案 无法扩展结构,但您可以将公共属性放入另一个结构中,并且您的结构可以包含这些常见结构.可以通过像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

点赞