캡슐화
Coddy의 Ruby 개발자를 위한 Rust 코스 레슨. 48개 중 33번째.
Ruby의 인스턴스 변수는 공개 리더를 자동으로 만들지 않으므로, 이 클래스는 secret 접근자를 추가하지 않고도 matches?를 노출합니다. Ruby의 리플렉션으로 내부 상태를 여전히 조사할 수 있습니다. 이는 보안 경계가 아니라 API 구성 방식입니다. Rust의 비공개 필드는 하나의 impl 블록만 접근할 수 있다는 규칙이 아니라 모듈의 비공개 범위를 따릅니다. 정의된 모듈 내 다른 코드에서는 해당 필드에 접근할 수 있지만, 외부 모듈에서는 공개 API를 사용합니다. 생성자는 불변 조건을 설정할 수 있으며, 메서드는 제한 없는 쓰기를 허용하지 않고도 이를 유지할 수 있습니다. 보호하는 상태 가까이에 유효성 검사를 두세요. 대상 예제는 제한적인 비교 연산을 통해 비공개 토큰 필드를 보여 줍니다.
Ruby: 완전한 프로그램
class Token
def initialize(secret)
@secret = secret
end
def matches?(candidate)
@secret == candidate
end
end
token = Token.new("mint")
puts token.matches?("mint")
puts token.matches?("sage")
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의 비공개 필드는 모듈 경계를 따릅니다. Ruby에서 접근자를 생략하고 리플렉션을 사용하는 것은 다른 모델입니다.
챌린지
쉬움잔액이 비공개인 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));
}
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
Ruby 개발자를 위한 Rust의 모든 레슨
직접 연습해 보세요: 온라인 Rust 컴파일러