구조체, 열거형, 트레이트
Rust Methods and impl Blocks
Attach behavior to a struct: methods with &self, changes with &mut self and constructors like new.
배울 내용
- impl blocks
- &self and &mut self
- Associated functions
Receiver → what the method can do
fn area(&self)readfn scale(&mut self, f)changefn new(w, h) -> SelfcreateFunctions that belong to a type
An impl block holds the functions that belong to a type. A method takes self as its first parameter and is called with a dot. A function without self, such as new, is called with the type name and ::.
&self borrows the rectangle for reading and &mut self borrows it for changing, which is why rect must be mut to call scale. Self is a short name for the type of the impl block. new and square are associated functions used as constructors.
핵심 포인트
- &self reads the value.
- &mut self changes it.
Rectangle::newhas no self: it is a constructor.
실행 가능한 Rust 예제
Rust
main.rs
struct Rectangle {
width: f64,
height: f64,
}
impl Rectangle {
fn new(width: f64, height: f64) -> Self {
Self { width, height }
}
fn square(size: f64) -> Self {
Self::new(size, size)
}
fn area(&self) -> f64 {
self.width * self.height
}
fn scale(&mut self, factor: f64) {
self.width *= factor;
self.height *= factor;
}
}
fn main() {
let mut rect = Rectangle::new(3.0, 4.0);
println!("area: {}", rect.area());
rect.scale(2.0);
println!("scaled: {} x {} = {}", rect.width, rect.height, rect.area());
println!("square: {}", Rectangle::square(5.0).area());
}
area: 12
scaled: 6 x 8 = 48
square: 25연습
예제를 온라인 컴파일러에서 열고 값을 바꾸거나 한 줄을 추가한 다음, 실행하기 전에 출력을 예상해 보세요. 그런 다음 일부러 코드를 망가뜨리고 컴파일러 메시지를 읽어 보세요.
이 레슨을 마쳤나요?
학습 완료로 표시하면 진행 상황을 기록할 수 있습니다.
진행 상황이 이 브라우저에 저장되어 있습니다 로그인하면 모든 기기에서 이어갈 수 있습니다.
챌린지로 연습하기
이 레슨에서 배운 내용으로 실제 문제를 풀어 보세요. 모든 챌린지는 브라우저에서 실행되며 즉시 테스트와 AI 리뷰를 받을 수 있습니다.
- 은행 계좌 규칙 입금과 출금 규칙으로 계좌 잔액을 보호하고, 잘못된 작업은 거부합니다. 쉬움
- Distance Between Points Compute the straight-line distance between two points. 쉬움