Back
Syntax
Study
Editor
Mode:
HTML
CSS
JavaScript
PHP
Reset
Run »
HTML / CSS / JS
use std::fs; use std::io; use std::path::Path; // Chain multiple fallible operations with ? fn read_number_from_file(path: &Path) -> Result<i64, Box<dyn std::error::Error>> { let content = fs::read_to_string(path)?; // io::Error -> Box<dyn Error> let n: i64 = content.trim().parse()?; // ParseIntError -> Box<dyn Error> Ok(n) } fn compute(path: &Path) -> Result<i64, Box<dyn std::error::Error>> { let n = read_number_from_file(path)?; if n < 0 { return Err("number must be non-negative".into()); } Ok(n * n) } // main can return Result — ? works here too fn main() -> Result<(), Box<dyn std::error::Error>> { // Write a temp file for demonstration let path = Path::new("number.txt"); fs::write(path, "42 ")?; match compute(path) { Ok(v) => println!("42 squared = {v}"), Err(e) => println!("error: {e}"), } // Try a bad file let bad = Path::new("missing.txt"); match compute(bad) { Ok(v) => println!("got {v}"), Err(e) => println!("expected error: {e}"), } // Cleanup fs::remove_file(path)?; Ok(()) }
Result
Open