Associated func/constructor

This commit is contained in:
Dan Buch 2017-12-31 11:04:17 -05:00
parent dbe2abdbe7
commit a8a1bdaaa8
Signed by: meatballhat
GPG Key ID: 9685130D8B763EA7

View File

@ -12,17 +12,22 @@ impl Rectangle {
fn can_hold(&self, other: &Rectangle) -> bool {
self.width > other.width && self.height > other.height
}
fn square(size: u32) -> Rectangle {
Rectangle { width: size, height: size }
}
}
fn main() {
let rect1 = Rectangle { width: 30, height: 50 };
let rect2 = Rectangle { width: 10, height: 40 };
let rect3 = Rectangle { width: 60, height: 45 };
let rect4 = Rectangle::square(3);
println!("Can rect1 hold rect2? {}", rect1.can_hold(&rect2));
println!("Can rect1 hold rect3? {}", rect1.can_hold(&rect3));
for (i, rect) in [rect1, rect2, rect3].iter().enumerate() {
for (i, rect) in [rect1, rect2, rect3, rect4].iter().enumerate() {
println!("rect{} has area {}", i+1, rect.area());
}
}