The following has a lot of duplicated code. What's the best way to refactor it?
I'm coming from Javascript where use composition to achieve the same result, but in rust seems to me that I have to re implement a lot of code.
I know there is a way using macros, but if the logic is more complex I'll end up with a large executable file since macros are inlined.
Link to the playground here
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!("---------------------");
}
}
Aucun commentaire:
Enregistrer un commentaire