Error Contracts
Lesson 28 of 48 in Coddy's Rust for C Developers course.
An error contract describes both the returned reason and the state left behind. A custom enum makes supported failures explicit and lets callers match every case without comparing error strings. Use #[derive(Debug, PartialEq)] when errors should be inspectable and comparable in tests. For operations promising unchanged state on failure, validate all preconditions before mutating, or build a temporary result and commit only after success. Returning Err does not roll back an earlier write. C status enums can express the same convention, but the caller must separately inspect the status and know which output parameters are valid. In Rust the successful payload is available only in Ok.
C
#include <stdio.h>
#include <string.h>
enum Status { OK, TOO_LONG };
enum Status append(char *dst, size_t capacity, const char *suffix) {
if (strlen(dst) + strlen(suffix) + 1 > capacity) return TOO_LONG;
strcat(dst, suffix);
return OK;
}
int main(void) {
char label[5] = "ab";
enum Status status = append(label, sizeof label, "cde");
printf("%s %s\n", status == TOO_LONG ? "too-long" : "ok", label);
return 0;
}Rust
#[derive(Debug, PartialEq)]
enum LabelError { TooLong }
fn append(label: &mut String, suffix: &str, max_bytes: usize) -> Result<(), LabelError> {
if label.len() + suffix.len() > max_bytes { return Err(LabelError::TooLong); }
label.push_str(suffix);
Ok(())
}
fn main() {
let mut label = String::from("ab");
let status = append(&mut label, "cde", 4);
println!("{} {}", if status == Err(LabelError::TooLong) { "too-long" } else { "ok" }, label);
}Safe Rust prevents memory misuse, not every logical state bug. Tests must check the state after rejected operations, not just the returned error.
Challenge
EasyImplement public DebitError variants NonPositive and Insufficient, deriving Debug and PartialEq, and pub fn debit(balance: &mut i32, amount: i32) -> Result<i32, DebitError> in account.rs. Starting balances are nonnegative and arithmetic fits i32. Reject an amount of zero or less with NonPositive; otherwise reject an amount greater than the balance with Insufficient. Every failure leaves balance unchanged. On success subtract amount and return the new balance. Input is starting balance followed by debit amounts. solve applies them in order and returns final|statuses, with statuses ok:new, nonpositive or insufficient, comma-separated. With no amounts the suffix is empty.
Implement the required exported APIs and return the result from exercise::solve(input: &str) -> String without a final newline. Do not print in editable code. The locked driver checks required APIs independently, reads all stdin, and prints the returned text with one final newline.
Your code goes in exercise.rs, account.rs. main.rs holds the supplied input/output code and cannot be edited.
Try it yourself
#![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();
// BEGIN PUBLIC API PROBES
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);
// END PUBLIC API PROBES
println!("{}", exercise::solve(&input));
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Rust for C Developers
1First Rust Programs
Run Rust ModulesOutput and CommentsModules and VisibilityBindings and TypesNumbers and CastsRecap: Storage Invoice4Ownership and Borrowing
Ownership and MovesShared BorrowsMutable BorrowsLifetimes and ViewsBorrowing Recap3Functions and Sequences
Functions and ReturnsArrays and SlicesVectors and IterationRecap: Record Readings6Absence and Failure
Option and MatchingResult and PropagationParsing and ValidationError ContractsFailure RecapPractice on your own: Online Rust compiler