Menu
CoddyTech

오류 계약

Coddy의 R 개발자를 위한 Rust 코스 레슨. 48개 중 28번째.

R 조건에는 핸들러가 실패 원인을 구분하는 데 사용하는 클래스 이름과 필드가 들어갈 수 있습니다. Rust 오류 열거형도 Result 내부에 의미 있는 대안을 지정하지만, 대상 계약은 정적으로 검사됩니다. 다음 예제에서는 호출자가 서식이 지정된 메시지를 분석하지 않아도 지원되지 않는 형식을 분류합니다. R 조건을 알리거나 Rust Err를 반환해도 이전 변경 사항, 특히 참조처럼 동작하는 환경을 통해 이루어진 변경 사항이 자동으로 복원되지는 않습니다. 거부 시 상태를 보존해야 한다면 업데이트를 커밋하기 전에 유효성을 검사하세요. 호출자가 안정적인 클래스나 변형을 바탕으로 복구 방법을 선택할 수 있도록 도메인 실패 분류를 표현 방식과 분리하세요. 실패를 표현하는 것만으로 트랜잭션이 제공되지는 않습니다.

R: 완성된 프로그램

check_format <- function(name) {
  if (name != "plain") {
    stop(structure(list(message = "format", call = NULL),
                   class = c("unsupported_format", "error", "condition")))
  }
}
tryCatch(check_format("binary"), unsupported_format = function(error) cat("format\n"))

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"),
    }
}

실패 처리와 롤백은 상태를 가진 API가 명시적으로 구현해야 하는 별개의 동작입니다.

challenge icon

챌린지

쉬움

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));
}
quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

R 개발자를 위한 Rust의 모든 레슨

직접 연습해 보세요: 온라인 Rust 컴파일러