Menu
CoddyTech

캡슐화

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

Swift의 private는 해당 선언과 조건을 충족하는 같은 파일의 확장으로 접근을 제한하는 반면, fileprivate는 소스 파일 전체에서 접근할 수 있게 합니다. Rust의 private 필드는 클래스나 개별 impl 경계가 아니라 정의된 모듈의 경계를 따릅니다. 해당 모듈의 다른 코드는 필드에 접근할 수 있지만, 외부 모듈은 공개된 API를 사용합니다. 두 토큰 유형은 공개된 비밀값 getter 없이 비교를 제공합니다. 제한 없는 쓰기를 노출하는 대신 생성 및 변경 작업 내부에서 불변 조건을 유지하세요. Rust의 pub는 가시성을 제어하며, 그 자체로 변경이나 소유권 이전을 허용하지 않습니다. 필드 이름을 사용할 수 있는 주체와 호출자가 값에 접근하는 방법을 구분하세요.

완전한 독립 실행형 Swift 프로그램:

struct Token {
    private let secret: String
    init(_ secret: String) { self.secret = secret }
    func matches(_ candidate: String) -> Bool { secret == candidate }
}
let token = Token("mint")
print(token.matches("mint"))
print(token.matches("sage"))

Swift 출력:

true
false

완전한 독립 실행형 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 출력:

true
false
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();
    // PUBLIC 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);
    // PUBLIC API 검사 끝
    println!("{}", exercise::solve(&input));
}
quiz icon실력 점검

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

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

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