Menu
Coddy logo textTech

다중 구현 블록

Coddy Rust 여정의 객체 지향 프로그래밍 섹션에 포함된 레슨. 61개 중 5번째.

Rust에서는 구조체의 메서드를 여러 impl 블록으로 나눌 수 있습니다. 모든 내용을 하나의 블록에 넣을 수도 있지만, 나누면 코드를 더 체계적이고 읽기 쉽게 만들 수 있습니다.

기능이 두 개의 구현 블록으로 나뉜 구조체입니다:

struct BankAccount {
    balance: f64,
}

// 생성자 및 기본 조회
impl BankAccount {
    fn new(initial: f64) -> BankAccount {
        BankAccount { balance: initial }
    }
    
    fn balance(&self) -> f64 {
        self.balance
    }
}

// 트랜잭션 메서드
impl BankAccount {
    fn deposit(&mut self, amount: f64) {
        self.balance += amount;
    }
    
    fn withdraw(&mut self, amount: f64) {
        self.balance -= amount;
    }
}

두 블록은 원활하게 함께 작동합니다. Rust는 이를 하나의 블록인 것처럼 처리합니다. 어떤 블록에 정의되어 있는지와 관계없이 모든 메서드를 호출할 수 있습니다:

fn main() {
    let mut account = BankAccount::new(100.0);
    account.deposit(50.0);
    println!("{}", account.balance()); // 150
}

이 패턴은 구조체가 커질수록 특히 유용해집니다. 생성자를 함께 그룹화하거나, 읽기 전용 메서드를 변경하는 메서드와 분리하거나, 기능별로 구성할 수 있습니다. 구조체가 가질 수 있는 impl 블록의 수에는 제한이 없습니다.

challenge icon

챌린지

쉬움

Player struct를 만들고 두 개의 fields를 정의하세요: name (String) 및 score (u32).

two separate implementation blocks에 걸쳐 struct의 methods를 구성하세요:

First impl block: Constructor 및 query:

  • new: name: String을 받고 score0으로 설정된 Player를 반환하는 associated function
  • get_score: &self를 받고 현재 score를 u32로 반환

Second impl block: Score modifications:

  • add_points: &mut selfpoints: u32를 받고 points를 score에 더함
  • reset_score: &mut self를 받고 score를 다시 0으로 설정

세 개의 입력을 받습니다:

  • First line: 플레이어의 이름 (String)
  • Second line: First round에 더할 points (u32)
  • Third line: Second round에 더할 points (u32)

Player::new를 사용하여 플레이어를 만들고, First round points를 더한 다음 score를 출력하세요. 그런 다음 score를 reset하고, Second round points를 더한 후 최종 score를 출력하세요.

예상 출력 형식:

{score_after_first_round}
{score_after_reset_and_second_round}

직접 해보기

use std::io;

// TODO: name (String)과 score (u32) 필드를 가진 Player 구조체 정의


// TODO: 첫 번째 impl 블록 - 생성자 및 조회 메서드 (new, get_score)


// TODO: 두 번째 impl 블록 - 점수 수정 메서드 (add_points, reset_score)


fn main() {
    let mut input = String::new();
    
    // 플레이어 이름 읽기
    io::stdin().read_line(&mut input).expect("Failed to read line");
    let name = input.trim().to_string();
    
    // 첫 번째 라운드 점수 읽기
    input.clear();
    io::stdin().read_line(&mut input).expect("Failed to read line");
    let first_round: u32 = input.trim().parse().expect("Invalid number");
    
    // 두 번째 라운드 점수 읽기
    input.clear();
    io::stdin().read_line(&mut input).expect("Failed to read line");
    let second_round: u32 = input.trim().parse().expect("Invalid number");
    
    // TODO: Player::new를 사용하여 플레이어 생성
    // TODO: 첫 번째 라운드 점수를 추가하고 점수 출력
    // TODO: 점수 초기화
    // TODO: 두 번째 라운드 점수를 추가하고 최종 점수 출력
}
quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

객체 지향 프로그래밍의 모든 레슨

직접 연습해 보세요: 온라인 Rust 컴파일러