Match와 열거형
Coddy의 Dart 개발자를 위한 Rust 코스 레슨. 48개 중 9번째.
Dart의 봉인된 클래스는 라이브러리가 닫힌 대안 집합을 설명할 수 있게 해 주며, switch 표현식은 그 집합과 빠짐없이 일치시킬 수 있습니다. Rust 열거형은 서로 다른 필드를 담을 수 있는 변형을 직접 선언합니다. Ready에는 페이지 수가 있고, Loading에는 페이로드가 없습니다. 패턴 매칭은 적절한 동작을 선택하고 해당 분기 안에서 관련 데이터를 사용할 수 있게 합니다. Dart의 클래스 패턴은 pages 속성을 읽는 반면, Rust의 열거형 패턴은 변형의 구조를 분해합니다. 두 예제 모두 로딩을 나타내는 마법의 센티널 숫자가 필요하지 않습니다. 새 대안을 추가했을 때 처리되지 않은 경우를 드러내고 싶다면 모든 경우를 포괄하는 분기를 피하세요. 이 과정에서는 match를 사용해 도메인 상태와 그에 필요한 동작을 명확히 표현합니다.
완전한 독립 실행형 Dart 프로그램:
sealed class DocumentState {}
class Ready extends DocumentState {
final int pages;
Ready(this.pages);
}
class Loading extends DocumentState {}
String describe(DocumentState state) => switch (state) {
Ready(:final pages) => 'pages=' + pages.toString(),
Loading() => 'loading',
};
void main() {
print(describe(Ready(9)));
print(describe(Loading()));
}
Dart 출력:
pages=9
loading
완전한 독립 실행형 Rust 프로그램:
enum DocumentState { Ready(u32), Loading }
fn describe(state: DocumentState) -> String {
match state {
DocumentState::Ready(pages) => format!("pages={}", pages),
DocumentState::Loading => "loading".to_string(),
}
}
fn main() {
println!("{}", describe(DocumentState::Ready(9)));
println!("{}", describe(DocumentState::Loading));
}
Rust 출력:
pages=9
loading
챌린지
쉬움액추에이터 명령 하나를 디코딩하세요. 입력은 forward amount, back amount 또는 wait이며, amount는 0부터 1000까지의 정수입니다. 필요한 공개 열거형: Command이며, 변형은 Forward(i32), Back(i32), Wait입니다. 필요한 API: pub fn displacement(command: Command) -> i32는 Forward의 경우 amount를, Back의 경우 amount의 음수를, Wait의 경우 0을 반환합니다. pub fn active(command: Command) -> bool는 이동량이 0이어도 Wait일 때만 false를 반환합니다. 열거형은 Clone, Copy를 파생하여 제공된 래퍼가 같은 명령을 두 함수에 모두 전달할 수 있도록 합니다. 출력은 displacement active입니다. 공개 API를 actuator.rs에 구현하세요. 제공된 exercise.rs는 유효한 입력을 파싱하고 해당 API를 호출합니다. 지정된 텍스트를 끝에 개행 없이 반환하세요. 잠금된 드라이버가 개행을 하나 추가합니다. API에서 출력하지 마세요. 모든 입력값은 명시된 범위를 만족합니다.
필요한 내보내기 API를 구현하고 exercise::solve(input: &str) -> String의 결과를 마지막 개행 없이 반환하세요. 편집 가능한 코드에서 출력하지 마세요. 잠금된 드라이버는 필요한 API를 개별적으로 확인하고, stdin 전체를 읽은 다음 반환된 텍스트를 마지막 개행 하나와 함께 출력합니다.
코드는 exercise.rs, actuator.rs에 작성하세요. main.rs에는 제공된 입출력 코드가 있으며 편집할 수 없습니다.
직접 해보기
#![allow(dead_code, unused_imports, unused_variables, unused_mut)]
mod exercise;
mod actuator;
use std::io::{self, Read};
fn main() {
let mut input=String::new();
io::stdin().read_to_string(&mut input).unwrap();
// PUBLIC API 검사 시작
assert_eq!(actuator::displacement(actuator::Command::Forward(37)), 37);
assert_eq!(actuator::displacement(actuator::Command::Back(37)), -37);
assert_eq!(actuator::displacement(actuator::Command::Wait), 0);
assert!(actuator::active(actuator::Command::Forward(0)));
assert!(actuator::active(actuator::Command::Back(0)));
assert!(!actuator::active(actuator::Command::Wait));
assert_eq!(actuator::displacement(actuator::Command::Forward(37)), 37);
// PUBLIC API 검사 끝
println!("{}", exercise::solve(&input));
}
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
Dart 개발자를 위한 Rust의 모든 레슨
직접 연습해 보세요: 온라인 Rust 컴파일러