캡슐화
Coddy의 Go 개발자를 위한 Rust 코스 레슨. 48개 중 33번째.
Go의 캡슐화는 일반적으로 패키지 경계를 따릅니다. 소문자로 시작하는 필드는 같은 패키지 안의 다른 코드에서 접근할 수 있습니다. Rust의 비공개 접근성은 모듈을 따릅니다. 공개 타입은 정의된 모듈 안에 비공개 필드를 두고 작은 공개 API를 제공할 수 있습니다.
아래 Rust 모듈은 상태를 닫는 것만 가능한 게이트를 공개합니다. 모듈 외부의 코드는 공개 연산을 호출할 수 있지만 비공개 필드를 직접 다시 열 수는 없습니다. Go 예제는 단일 패키지 프로그램이므로 소문자 필드에 main에서 접근할 수 있습니다. 별도의 패키지에서 Gate를 내보내면 호출자는 해당 필드에 접근할 수 없습니다.
완성된 Go 비교 프로그램:
package main
import "fmt"
type Gate struct { closed bool }
func NewGate() Gate { return Gate{} }
func (g *Gate) Close() { g.closed = true }
func (g Gate) IsClosed() bool { return g.closed }
func main() { g := NewGate(); g.Close(); fmt.Println(g.IsClosed()) }Go 출력:
true완성된 Rust 교육용 프로그램:
mod gate {
pub struct Gate { closed: bool }
impl Gate {
pub fn new() -> Gate { Gate { closed: false } }
pub fn close(&mut self) { self.closed = true; }
pub fn is_closed(&self) -> bool { self.closed }
}
}
fn main() {
let mut g = gate::Gate::new();
g.close();
println!("{}", g.is_closed());
}Rust 출력:
true챌린지
쉬움잔액이 비공개인 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));
}
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
Go 개발자를 위한 Rust의 모든 레슨
직접 연습해 보세요: 온라인 Rust 컴파일러