캡슐화
Coddy의 C 개발자를 위한 Rust 코스 레슨. 48개 중 33번째.
Rust의 프라이버시는 모듈 경계에서 적용됩니다. 공개 구조체도 필드는 비공개로 유지하면서 자체 규칙을 보존하는 작업만 공개할 수 있습니다. C에서는 헤더에서 불완전한 타입으로 구조체 정의를 숨기고, 구현 함수가 완전한 레코드에 접근할 수 있습니다. Rust에서는 모듈과 pub를 사용해 이러한 경계를 직접 표현합니다. 이 코드는 호출하는 코드에 저장된 문자열을 직접 접근할 수 있게 하지 않으면서 태그 비교를 공개합니다. 실패할 수 있는 작업에서는 먼저 검증하고, 모든 검사가 성공한 뒤에만 변경하세요.
C
#include <stdio.h>
#include <string.h>
struct Tag;
int tag_matches(const struct Tag *tag, const char *text);
struct Tag { const char *text; };
int tag_matches(const struct Tag *tag, const char *text) { return strcmp(tag->text, text) == 0; }
int main(void) {
struct Tag tag = {"blue"};
printf("%d %d\n", tag_matches(&tag, "blue"), tag_matches(&tag, "Blue"));
return 0;
}Rust
mod tag {
pub struct Tag { text: String }
impl Tag {
pub fn new(text: &str) -> Tag { Tag { text: text.to_string() } }
pub fn matches(&self, text: &str) -> bool { self.text == text }
}
}
fn main() {
let t = tag::Tag::new("blue");
println!("{} {}", t.matches("blue"), t.matches("Blue"));
}구조체에 pub를 붙여도 비공개 필드가 공개되지는 않습니다. 다른 모듈에서는 공개 메서드를 호출하세요.
챌린지
쉬움잔액을 비공개로 유지하는 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();
// 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));
}
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
C 개발자를 위한 Rust의 모든 레슨
직접 연습해 보세요: 온라인 Rust 컴파일러