Menu
CoddyTech

캡슐화

Coddy의 Python 개발자를 위한 Rust 코스 레슨. 48개 중 33번째.

Python은 접근을 유도하기 위해 관례, 속성, 이름 맹글링을 사용합니다. 앞에 밑줄 하나를 붙인다고 해서 비공개 필드로 강제되는 것은 아닙니다. Rust에서는 모듈 경계를 기준으로 비공개가 강제됩니다. 공개 구조체는 필드를 숨기고 공개 연관 함수와 메서드를 통해 제한된 API를 제공할 수 있습니다. 이 API는 표현 방식의 선택과 불변 조건을 보호할 수 있습니다. 이 예제에서는 비공개 토큰 필드를 직접 수정할 수 없도록 하면서, 해당 토큰이 후보와 일치하는지 확인하는 기능을 제공합니다. 정의 모듈 내부의 메서드는 비공개 필드를 사용할 수 있습니다. 예제 전체가 하나의 소스 파일에 있더라도 부모 모듈의 코드는 공개 인터페이스를 사용해야 합니다.

Python: 완전한 프로그램

class Token:
    def __init__(self, secret):
        self._secret = secret
    def matches(self, candidate):
        return self._secret == candidate
token = Token("mint")
print(token.matches("mint"))
print(token._secret)

Rust: 완전한 프로그램

mod access {
    pub struct Token { secret: String }
    impl Token {
        pub fn fixed() -> Self { Token { secret: String::from("mint") } }
        pub fn matches(&self, candidate: &str) -> bool { self.secret == candidate }
    }
}
fn main() {
    let token = access::Token::fixed();
    println!("{}", token.matches("mint"));
    println!("{}", token.matches("sage"));
}

Rust의 필드 비공개 여부는 모듈과 연결되며, Python식 밑줄 표기나 클래스 상속 규칙과는 관련이 없습니다.

challenge icon

챌린지

쉬움

잔액을 비공개로 유지하는 wallet::Wallet을 구현하세요. Wallet::new(balance: i32) -> Option<Wallet>은 음수 잔액을 거부합니다. balance(&self) -> i32는 잔액을 읽습니다. deposit(&mut self, amount: i32) -> bool는 음수 금액을 거부하고, 그 외의 경우 금액을 더합니다. withdraw(&mut self, amount: i32) -> bool는 음수 금액이나 잔액보다 큰 금액을 거부합니다. 거부된 모든 작업은 상태를 변경하지 않으며, 0은 허용됩니다. solve는 0 이상인 초기 잔액에 이어 명령 쌍 d amount 또는 w amount를 읽습니다. 각 결과를 한 줄에 true:balance 또는 false:balance로 반환하고, 그 뒤에 balance:n을 반환하세요. 모든 값과 중간 잔액은 i32의 범위에 들어갑니다.

필수로 내보내야 하는 API를 구현하고, exercise::solve(input: &str) -> String의 결과를 마지막 개행 없이 반환하세요. 편집 가능한 코드에서는 출력하지 마세요. 잠긴 드라이버는 필수 API를 독립적으로 확인하고, 표준 입력을 모두 읽은 다음 반환된 텍스트를 마지막 개행 하나와 함께 출력합니다.

코드는 exercise.rs, wallet.rs에 작성하세요. main.rs에는 제공된 입력/출력 코드가 있으며 수정할 수 없습니다.

직접 해보기

#![allow(dead_code, unused_imports, unused_variables, unused_mut)]
mod exercise;
mod wallet;
use std::io::{self, Read};
fn main() {
    let mut input=String::new();
    io::stdin().read_to_string(&mut input).unwrap();
    // 공개 API 검사 시작
assert!(wallet::Wallet::new(-17).is_none());
let mut a = wallet::Wallet::new(43).unwrap(); let b = wallet::Wallet::new(6).unwrap();
assert!(!a.withdraw(44)); assert_eq!(a.balance(), 43);
assert!(!a.withdraw(-2)); assert!(!a.deposit(-8)); assert_eq!(a.balance(), 43);
assert!(a.withdraw(43)); assert!(a.withdraw(0)); assert_eq!(a.balance(), 0);
assert!(a.deposit(11)); assert!(a.deposit(0)); assert_eq!(a.balance(), 11);
assert_eq!(b.balance(), 6); assert!(a.withdraw(4)); assert_eq!(a.balance(), 7);
    // 공개 API 검사 끝
    println!("{}", exercise::solve(&input));
}
quiz icon실력 점검

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

Python 개발자를 위한 Rust의 모든 레슨

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