Menu
CoddyTech

캡슐화

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

Dart의 밑줄(underscore) 이름은 선언된 클래스가 아니라 해당 라이브러리에 대해 private입니다. 따라서 다른 라이브러리의 클라이언트는 접근할 수 없더라도 동일한 Dart 파일의 다른 코드는 _mode에 접근할 수 있습니다. Rust의 가시성은 모듈을 따릅니다. public Theme 타입은 접근자를 노출하면서 theme 모듈 내부에 해당 필드를 숨길 수 있습니다. 부모 모듈은 단지 해당 타입의 이름을 참조할 수 있다고 해서 그 필드를 읽을 수 있는 것은 아닙니다. 두 예제 모두 의도된 API를 통해 quiet을 반환합니다. 비공개성(Privacy)은 표현 경계를 보호하지만, 메서드는 여전히 도메인 계약을 유지해야 합니다. 변경 사항을 적용하기 전에 검증하고 호출자에게 필요한 관찰 항목만 노출하세요. 두 설계 모두 상속을 필요로 하지 않습니다.

완전한 단독 Dart 프로그램:

class Theme {
  final String _mode = 'quiet';
  String mode() => _mode;
}
void main() { print(Theme().mode()); }

Dart 출력:

quiet

완전한 단독 Rust 프로그램:

mod theme {
    pub struct Theme { mode: &'static str }
    impl Theme {
        pub fn new() -> Theme { Theme { mode: "quiet" } }
        pub fn mode(&self) -> &str { self.mode }
    }
}
fn main() { println!("{}", theme::Theme::new().mode()); }

Rust 출력:

quiet
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실력 점검

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

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

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