오류 계약
Coddy의 PHP 개발자를 위한 Rust 코스 레슨. 48개 중 28번째.
PHP 예외 하위 클래스와 Rust 오류 열거형을 사용하면 사람이 읽을 수 있는 메시지를 분석하지 않고도 도메인 오류를 구분할 수 있습니다. 이 예제에서는 지원하지 않는 형식을 유형이나 변형으로 분류합니다. Rust의 Result는 오류 유형을 함수 시그니처의 일부로 만들어 호출자가 의미 있는 경우를 패턴 매칭할 수 있게 합니다. 예외를 던지거나 Err를 반환해도 앞서 이루어진 변경 사항이 자동으로 되돌려지지는 않습니다. 거부 시 상태가 바뀌지 않는다고 보장하는 상태 유지 작업은 변경 사항을 적용하기 전에 검증하거나, 변경 사항을 의도적으로 복원해야 합니다. 이 예제는 상태를 유지하지 않으므로 그 자체로 이러한 트랜잭션 동작을 제공하지 않습니다. 호출자가 복구, 재시도 또는 요청 거부 여부를 결정할 수 있도록 표시와 분류를 분리하세요.
PHP: 완전한 프로그램
<?php
declare(strict_types=1);
class UnsupportedFormat extends RuntimeException {}
function checkFormat(string $name): void {
if ($name !== "plain") throw new UnsupportedFormat("format");
}
try { checkFormat("binary"); }
catch (UnsupportedFormat $error) { echo "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"),
}
}실패 신호 전달과 상태 롤백은 서로 별개의 계약입니다.
챌린지
쉬움공개 DebitError 변형인 NonPositive와 Insufficient를 구현하고, Debug와 PartialEq를 파생하며, account.rs에 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();
// 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));
}
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
PHP 개발자를 위한 Rust의 모든 레슨
직접 연습해 보세요: 온라인 Rust 컴파일러