오류 계약
Coddy의 Swift 개발자를 위한 Rust 코스 레슨. 48개 중 28번째.
Swift의 Error 준수 열거형은 실패를 분류해 catch에서 처리할 수 있고, Rust의 오류 열거형은 Result의 대안을 분류해 match에서 처리할 수 있습니다. 복구 방법이 원인에 따라 달라지는 경우, 호출자가 표시용 텍스트를 분석하게 하는 대신 구조화된 구분 정보를 제공하세요. 이 프로그램은 형식 오류를 식별합니다. 어느 방식도 트랜잭션 롤백을 제공하지 않습니다. 필드를 변경한 다음 실패를 반환해도 구현에서 되돌리지 않는 한 변경 사항은 그대로 남습니다. 거부 시 상태가 변경되지 않는다고 API가 약속한다면, 값을 변경하기 전에 먼저 유효성을 검사하세요. 예상 가능한 실패는 선언된 계약을 통해 전파하고, 일반적인 입력 유효성 검사에 치명적인 트랩을 사용하지 마세요. 유용한 메시지는 정확한 오류 유형을 대체하는 것이 아니라 보완합니다.
완전한 독립 실행형 Swift 프로그램:
enum ModeError: Error { case format }
func mode(_ text: String) throws -> String {
guard text == "ready" else { throw ModeError.format }
return text
}
do { print(try mode("bad")) }
catch ModeError.format { print("format") }
catch { print("other") }
Swift 출력:
format
완전한 독립 실행형 Rust 프로그램:
#[derive(Debug)]
enum FormatError { Unsupported }
fn check_format(name: &str) -> Result<(), FormatError> {
if name == "plain" { Ok(()) } else { Err(FormatError::Unsupported) }
}
fn main() {
match check_format("binary") {
Ok(()) => println!("ready"),
Err(FormatError::Unsupported) => println!("format"),
}
}Rust 출력:
format
챌린지
쉬움공개 DebitError 변형 NonPositive와 Insufficient를 구현하고, Debug와 PartialEq를 파생하며, account.rs에 pub fn debit(balance: &mut i32, amount: i32) -> Result<i32, DebitError>를 구현하세요. 시작 잔액은 음수가 아니며 산술 연산 결과는 i32 범위에 들어갑니다. 금액이 0 이하이면 NonPositive로 거부하고, 그렇지 않은 경우 잔액보다 큰 금액은 Insufficient로 거부하세요. 실패할 때마다 잔액은 변경되지 않습니다. 성공하면 금액을 빼고 새로운 잔액을 반환하세요. 입력은 시작 잔액 다음에 출금 금액이 이어집니다. solve는 금액을 순서대로 적용하고, 쉼표로 구분된 상태 ok:new, nonpositive 또는 insufficient와 함께 final|statuses를 반환합니다. 금액이 없으면 접미 문자열은 비어 있습니다.
필수로 내보내야 하는 API를 구현하고, 마지막 개행 문자 없이 exercise::solve(input: &str) -> String의 결과를 반환하세요. 편집 가능한 코드에서는 출력하지 마세요. 잠긴 드라이버는 필수 API를 독립적으로 검사하고, 표준 입력을 모두 읽은 다음 반환된 텍스트를 마지막 개행 문자 하나와 함께 출력합니다.
코드는 exercise.rs, account.rs에 작성하세요. main.rs에는 제공된 입력/출력 코드가 있으며 수정할 수 없습니다.
직접 해보기
#![allow(dead_code, unused_imports, unused_variables, unused_mut)]
mod exercise;
mod account;
use std::io::{self, Read};
fn main() {
let mut input=String::new();
io::stdin().read_to_string(&mut input).unwrap();
// PUBLIC API 테스트 시작
let mut balance = 37;
assert_eq!(account::debit(&mut balance, 12), Ok(25));
assert_eq!(account::debit(&mut balance, 26), Err(account::DebitError::Insufficient));
assert_eq!(balance, 25);
assert_eq!(account::debit(&mut balance, -4), Err(account::DebitError::NonPositive));
assert_eq!(balance, 25);
assert_eq!(account::debit(&mut balance, 0), Err(account::DebitError::NonPositive));
assert_eq!(balance, 25);
assert_eq!(account::debit(&mut balance, 25), Ok(0));
assert_eq!(account::debit(&mut balance, 1), Err(account::DebitError::Insufficient));
assert_eq!(balance, 0);
// PUBLIC API 테스트 종료
println!("{}", exercise::solve(&input));
}
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
Swift 개발자를 위한 Rust의 모든 레슨
직접 연습해 보세요: 온라인 Rust 컴파일러