오류 계약
Coddy의 Ruby 개발자를 위한 Rust 코스 레슨. 48개 중 28번째.
Ruby의 사용자 지정 예외 클래스는 rescue에서 실패 범주를 구분할 수 있고, Rust의 오류 열거형은 명시적인 반환 유형으로 여러 대안을 인코딩합니다. 호출자에게 서로 다른 복구 동작이 필요한 경우 의미 있는 변형을 기준으로 match하고, 사람이 읽을 수 있는 메시지는 표시용으로 남겨 두세요. 원본은 FormatError를 잡고, 대상은 열거형의 실패를 match합니다. Result 반환 유형도 raise와 마찬가지로 롤백을 보장하지 않습니다. 오류가 발생하기 전에 수행한 대입은 코드에서 되돌리지 않는 한 그대로 남습니다. 변경 없이 거부하는 계약을 원한다면, 상태를 커밋하기 전에 변경 예정 상태를 검증하세요. 오류를 전파할 때는 모든 실패를 유효한 0이나 빈 문자열로 바꾸지 말고 정보를 보존해야 합니다.
Ruby: 완전한 프로그램
class FormatError < StandardError; end
def parse_mode(text)
raise FormatError, "format" unless text == "ready"
text
end
begin
parse_mode("bad")
rescue FormatError => error
puts error.message
end
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"),
}
}실패 표현과 트랜잭션 방식의 상태 업데이트는 서로 별개의 설계 결정입니다.
챌린지
쉬움account.rs에 공개 DebitError 변형 NonPositive와 Insufficient를 구현하고, Debug와 PartialEq를 파생하며, pub fn debit(balance: &mut i32, amount: i32) -> Result<i32, DebitError>를 구현하세요. 시작 잔액은 음수가 아니며 산술 연산 결과는 i32에 들어갑니다. 금액이 0 이하이면 NonPositive로 거부하고, 그렇지 않은 경우 금액이 잔액보다 크면 Insufficient로 거부하세요. 실패하면 잔액은 변경되지 않습니다. 성공하면 금액을 빼고 새 잔액을 반환하세요. 입력은 시작 잔액 뒤에 인출 금액이 이어집니다. solve는 인출 금액을 순서대로 처리하고 final|statuses를 반환합니다. 상태는 ok:new, nonpositive 또는 insufficient이며 쉼표로 구분됩니다. 인출 금액이 없으면 접미 부분은 비어 있습니다.
필수로 내보내야 하는 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();
// 공개 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);
// 공개 API 검사 끝
println!("{}", exercise::solve(&input));
}
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
Ruby 개발자를 위한 Rust의 모든 레슨
직접 연습해 보세요: 온라인 Rust 컴파일러