캡슐화
Coddy의 GDScript 개발자를 위한 Rust 코스 레슨. 48개 중 33번째.
GDScript의 밑줄은 비공개로 사용할 의도를 나타내지만, 다른 스크립트가 멤버를 읽는 것을 막지는 않습니다. 속성을 사용하면 권장되는 접근자 경로를 제공할 수 있지만, 이름만으로는 프라이버시가 강제되지 않습니다. Rust는 모듈 경계를 넘어 필드의 가시성을 검사합니다. 공개된 Token은 secret 필드를 숨기면서 생성 및 일치 확인 메서드를 공개합니다. 인라인 모듈이 같은 소스 파일에 있더라도 부모 모듈은 해당 인터페이스를 사용해야 합니다. 이 예제에서는 호출자가 저장된 토큰을 직접 변경하지 않고 후보 값이 일치하는지 확인할 수 있습니다. 좁은 API는 그 메서드도 의도한 불변 조건을 유지할 때만 표현 방식의 선택을 보호합니다. 가시성은 상속 및 유효성 검사와는 별개입니다.
GDScript: 전체 프로그램
extends SceneTree
class Token:
var _secret: String
func _init(value: String):
_secret = value
func matches(candidate: String) -> bool:
return _secret == candidate
func _init():
var token = Token.new("mint")
print(token.matches("mint"))
print(token._secret)
quit()
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의 모듈 프라이버시는 밑줄 표기와 관계없이 강제됩니다. GDScript에서 직접 읽는 부분은 규칙이 더 느슨한 관례임을 보여 줍니다.
챌린지
쉬움잔액이 비공개인 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는 음수가 아닌 초기 잔액에 이어 명령과 금액의 쌍인 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));
}
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
GDScript 개발자를 위한 Rust의 모든 레슨
직접 연습해 보세요: 온라인 Rust 컴파일러