Result and Propagation
Lesson 26 of 48 in Coddy's Rust for JavaScript Developers course.
Any JavaScript function can throw, and nothing in its definition says so. The exception travels through every caller until some try/catch stops it, and the caught value can be anything: an Error, a string, a number, even undefined. Rust Result<T, E> puts success and failure into the return type, so callers can see the failure and must choose how to handle the value. The examples reject an unavailable feature inside a helper that the caller uses. In JavaScript, start passes the exception on invisibly. In Rust, ? marks the exact point where an error leaves start early, and it works only because start itself returns a Result. The ? operator does not catch a panic, and it never continues with a made-up value. Choose an error representation that tells callers what they need. A successful result can hold unit, (), when the operation matters but there is nothing more to return.
Complete standalone JavaScript program:
function openFeature(enabled) {
if (!enabled) throw new Error("disabled");
return "ready";
}
function start(enabled) {
const text = openFeature(enabled);
return `started ${text}`;
}
try {
console.log(start(false));
} catch (error) {
console.log(error instanceof Error ? error.message : String(error));
}
JavaScript output:
disabled
Complete standalone Rust program:
fn open_feature(enabled: bool) -> Result<&'static str, &'static str> {
if enabled { Ok("ready") } else { Err("disabled") }
}
fn start(enabled: bool) -> Result<String, &'static str> {
let text = open_feature(enabled)?;
Ok(format!("started {}", text))
}
fn main() {
match start(false) {
Ok(text) => println!("{}", text),
Err(reason) => println!("{}", reason),
}
}
Rust output:
disabled
Challenge
EasyImplement pub fn exact_divide(a: i32, b: i32) -> Result<i32, String> and pub fn sum_quotients(pairs: &[(i32, i32)]) -> Result<i32, String> in division.rs. Division returns Err("zero") for a zero divisor, Err("fraction") for a nonzero remainder, otherwise the exact integer quotient. Sum evaluates pairs in order and returns the sum, stopping at and returning the first error; empty input is Ok(0). All inputs and intermediate values fit i32. solve reads whitespace-separated numerator/denominator pairs and returns ok:total or error:reason. The number of input integers is always even.
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, division.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 division;
use std::io::{self, Read};
fn main() {
let mut input=String::new();
io::stdin().read_to_string(&mut input).unwrap();
// BEGIN PUBLIC API PROBES
assert_eq!(division::exact_divide(35, -7), Ok(-5));
assert_eq!(division::exact_divide(0, 9), Ok(0));
assert_eq!(division::exact_divide(1, 0), Err(String::from("zero")));
assert_eq!(division::exact_divide(-8, 3), Err(String::from("fraction")));
assert_eq!(division::sum_quotients(&[(24, 6), (-15, 5)]), Ok(1));
assert_eq!(division::sum_quotients(&[]), Ok(0));
assert_eq!(division::sum_quotients(&[(7, 2), (9, 0)]), Err(String::from("fraction")));
// 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 JavaScript 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