캡슐화
Coddy의 PHP 개발자를 위한 Rust 코스 레슨. 48개 중 33번째.
PHP의 private 속성은 클래스 접근 규칙에 따라 제어됩니다. Rust의 비공개 규칙은 필드를 하나의 impl 블록으로만 제한하는 대신 모듈을 기준으로 합니다. 공개 Rust Token은 생성 및 일치 확인 작업을 제공하면서 부모 모듈에서 비밀 값을 숨깁니다. 두 예제 모두 비밀 값에 대한 호출자의 직접적인 변경을 허용하지 않고 API를 통해 일치하는 후보와 일치하지 않는 후보를 테스트합니다. 정의된 Rust 모듈의 다른 코드는 비공개 필드에 접근할 수 있으므로 올바른 모듈 경계에 불변 조건을 배치하세요. 캡슐화는 모든 공개 작업이 약속된 규칙도 지킬 때만 표현 방식의 선택을 보호합니다. 공개 범위 지정자는 입력 검증을 대신하지 않습니다.
PHP: 완전한 프로그램
<?php
declare(strict_types=1);
final class Token {
public function __construct(private string $secret) {}
public function matches(string $candidate): bool { return $this->secret === $candidate; }
}
$token = new Token("mint");
echo ($token->matches("mint") ? "true" : "false"), "\n";
echo ($token->matches("sage") ? "true" : "false"), "\n";
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의 모듈 비공개 규칙은 PHP의 클래스 한정 private 접근 범위와 다릅니다. 경계를 신중하게 선택하세요.
챌린지
쉬움잔액을 비공개로 하는 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));
}
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
PHP 개발자를 위한 Rust의 모든 레슨
직접 연습해 보세요: 온라인 Rust 컴파일러