struct Rectangle {
width: u32,
height: u32,
}
impl Rectangle {
fn area(&self) -> u32 {
self.width * self.height
}
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 };
println!("The area of the rectangle is {} square pixels.", rect1.area());
println!("Can rect1 hold rect2? {}", rect1.can_hold(&rect2));
println!("Can rect1 hold rect3? {}", rect1.can_hold(&rect3));
let square = Rectangle::square(10);
println!("The area of the square is {} square pixels.", square.area());
}
Rust
복사
$ cargo run
The area of the rectangle is 1500 square pixels.
Can rect1 hold rect2? true
Can rect1 hold rect3? false
The area of the square is 100 square pixels.
Shell
복사
1.
구조체(struct) 선언하기
먼저, Rectangle 구조체를 선언합니다.
Rectangle 구조체는 width와 height 두 개의 필드를 가지고 있습니다. 두 필드 모두 u32 타입입니다.
2.
구조체의 구현체(impl) 정의하기
다음으로, Rectangle 구조체에 대한 동작(메소드)을 정의하기 위해 구현체(impl)를 정의합니다.
위의 코드에서 impl은 Rectangle 구조체에 대한 구현을 나타냅니다. 이 구현은 area(), can_hold(), square()의 3개의 메소드를 정의합니다.
•
area() 메소드는 &self를 인자로 받아 u32 타입의 값을 반환합니다. 이 메소드는 Rectangle의 너비(width)와 높이(height)를 곱한 값인 직사각형의 넓이를 계산합니다.
•
can_hold() 메소드는 &self와 &Rectangle을 인자로 받아 bool 값을 반환합니다. 이 메소드는 인자로 받은 다른 Rectangle 구조체가 self 구조체를 포함할 수 있는지 여부를 확인합니다. 만약 다른 구조체가 포함될 수 있다면 true를 반환하고, 그렇지 않으면 false를 반환합니다.
•
square() 메소드는 size: u32를 인자로 받아 Rectangle 구조체를 반환합니다. 이 메소드는 주어진 size 값으로 정사각형 Rectangle 구조체를 생성합니다.
컬렉션 찾아보기
시리즈