가변 메서드
Coddy Rust 여정의 객체 지향 프로그래밍 섹션에 포함된 레슨. 61개 중 3번째.
때로는 메서드가 단순히 데이터를 읽는 것 이상의 작업을 해야 합니다. 데이터를 변경해야 할 수도 있습니다. 구조체의 필드를 수정할 수 있는 메서드를 만들려면 &mut self 대신 &self를 사용합니다.
mut 키워드는 변경 가능한 빌림을 나타내며, 메서드가 인스턴스의 내부 상태를 변경할 수 있는 권한을 부여합니다.
struct Counter {
value: i32,
}
impl Counter {
fn increment(&mut self) {
self.value += 1;
}
fn decrement(&mut self) {
self.value -= 1;
}
fn get(&self) -> i32 {
self.value
}
}
increment와 decrement는 value를 수정하기 때문에 &mut self를 사용하는 반면, get은 데이터만 읽으므로 &self를 사용한다는 점에 유의하세요.
가변 메서드를 호출할 때는 인스턴스 자체를 가변으로 선언해야 합니다:
fn main() {
let mut counter = Counter { value: 0 };
counter.increment();
counter.increment();
println!("{}", counter.get()); // 2
counter.decrement();
println!("{}", counter.get()); // 1
}
instance를 생성할 때 mut 키워드를 잊으면 Rust는 해당 instance에서 &mut self 메서드를 호출하지 못하게 합니다. 이를 통해 데이터가 변경될 수 있는 경우를 항상 인지할 수 있습니다.
챌린지
쉬움단일 필드인 balance(i32)를 가진 BankAccount struct를 생성하세요.
BankAccount에 대해 세 가지 methods를 포함하는 implementation block을 추가하세요.
deposit:&mut self와amount: i32를 받아 금액을 잔액에 더합니다withdraw:&mut self와amount: i32를 받아 금액을 잔액에서 뺍니다get_balance:&self를 받아 현재 잔액을i32로 반환합니다
세 개의 입력을 받습니다.
- 첫 번째 줄: initial balance (i32)
- 두 번째 줄: deposit amount (i32)
- 세 번째 줄: withdrawal amount (i32)
initial balance로 mutable BankAccount instance를 생성한 다음, 주어진 금액을 deposit하고, 주어진 금액을 withdraw한 후, final balance를 출력하세요.
Expected output format:
{final_balance}직접 해보기
use std::io;
// TODO: 여기에 BankAccount 구조체를 정의하세요
// TODO: deposit, withdraw, get_balance 메서드가 있는 BankAccount의 구현 블록을 추가하세요
fn main() {
let mut input = String::new();
// 초기 잔액 읽기
io::stdin().read_line(&mut input).expect("Failed to read line");
let initial_balance: i32 = input.trim().parse().expect("Invalid number");
input.clear();
// 입금 금액 읽기
io::stdin().read_line(&mut input).expect("Failed to read line");
let deposit_amount: i32 = input.trim().parse().expect("Invalid number");
input.clear();
// 출금 금액 읽기
io::stdin().read_line(&mut input).expect("Failed to read line");
let withdraw_amount: i32 = input.trim().parse().expect("Invalid number");
// TODO: initial_balance로 가변 BankAccount 인스턴스를 생성하세요
// TODO: deposit_amount로 deposit을 호출하세요
// TODO: withdraw_amount로 withdraw를 호출하세요
// TODO: get_balance를 사용하여 최종 잔액을 출력하세요
}이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
객체 지향 프로그래밍의 모든 레슨
직접 연습해 보세요: 온라인 Rust 컴파일러