liveBook · Manning

Result type

As explained in Code Like a Pro in Rust

Result is a Rust enum representing either successful computation with a value or failure with an error.

A `Result<T, E>` represents an operation that either succeeds with a value or fails with an error. It is commonly used as a function return type for fallible operations. section 4.6

Listing 4.15 Snippet of std::result::Result, from http://mng.bz/M97Q
pub enum Result<T, E> {
   Ok(T),
   Err(E),
}

The two variants encode success and failure, with separate types for the value and error. section 4.6

Use `?` to propagate an error immediately or continue with the successful value. When the error types differ, implement `From` to convert between them. section 4.6

fn read_file(name: &str) -> Result<String, Error> {
    use std::fs::File;
    use std::io::prelude::*;
 
    let mut file = File::open(name)?;      #1
    let mut contents = String::new();
    file.read_to_string(&mut contents)?;   #2
    Ok(contents)
}

This file-reading function propagates errors from both file opening and reading, then returns the contents as `Ok`. section 4.6

For crate APIs, return a crate-specific error type so callers can identify where an error originates. Fallible conversions use `TryFrom` and `TryInto`, which return `Result` rather than requiring a panic on failure. section 4.6 section 4.7.1

Handle I/O and other edge cases instead of bypassing them with `unwrap()`; testing should focus on logic, including conversions that can fail. section 6.4

How Code Like a Pro in Rust covers it

How deep it goes
Shows the enum variants and works through error propagation, custom errors, and conversions without exploring enum internals.
Examples
Demonstrates reading a file with `?`, converting I/O errors, and returning file contents as a `Result`.
What you can do after
Apply it to return fallible results, propagate I/O errors, and convert errors into a crate-specific type.
How it connects
Connects error handling to the `?` operator, the `From` trait, fallible conversions, and I/O.

Also explained in

Compare how 8 books explain result type →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Code Like a Pro in Rust. The section links point to the parts of the book it draws on.