gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 07:55:32 24 4
gpt4 key购买 nike

<分区>

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

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

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