728x90
반응형
Method
- 함수와 유사하며, fn 키워드와 이름으로 메서드를 선언하고 매개 변수와 반환 값을 가질 수 있고 메서드가 다른 곳에서 호출될 때 실행되는 일부 코드를 포함한다.
- 함수와 달리 메서드는 구조체의 컨텍스트 내에서 정의되며, 첫번째 매개변수는 항상 self 메서드가 속한 구조체의 인스턴스를 나타내며 호출된다.
1) 방법 정의
impl Rectangle {
fn width(&self) -> bool {
self.width > 0
}
}
fn main() {
let rect1 = Rectangle {
width: 30,
height: 50,
};
if rect1.width() {
println!("The rectangle has a nonzero width; it is {}", rect1.width);
}
}
2) 더 많은 매개변수
fn main() {
let rect1 = Rectangle {
width: 30,
height: 50,
};
let rect2 = Rectangle {
width: 10,
height: 40,
};
let rect3 = Rectangle {
width: 60,
height: 45,
};
println!("Can rect1 hold rect2? {}", rect1.can_hold(&rect2));
println!("Can rect1 hold rect3? {}", rect1.can_hold(&rect3));
}
impl Rectangle {
fn area(&self) -> u32 {
self.width * self.height
}
fn can_hold(&self, other: &Rectangle) -> bool {
self.width * self.height > rect.width * rect.height
// self.width > other.width && self.height > other.height
}
}
[결과]
Can rect1 hold rect2? true
Can rect1 hold rect3? false
3) 정사각형을 만드는 인스턴스 생성
Self를 이용한 인스턴스 생성을 할 때는 구조체명::메소드명(매개변수) 의 형태로 만들 수 있다.
impl Rectangle {
fn square(size: u32) -> Self {
Self {
width: size,
height: size,
}
}
}
fn main(){
let square = dbg!(Rectangle::square(30)); // 이와 같은 형태!
}
[결과]
Rectangle::square(30) = Rectangle { width: 30, height: 30, }
728x90
반응형
'Language > Rust' 카테고리의 다른 글
[Rust]Structure 구조체 (0) | 2022.12.28 |
---|---|
[Rust]소유권 - string slice (0) | 2022.12.28 |
[Rust]소유권 - referrence, borrowing (0) | 2022.12.28 |
[Rust]Ownership 소유권 (0) | 2022.12.23 |
[Rust]Control Flow 제어문 (0) | 2022.12.22 |