expect_with 1.0.0

Expect with formatting
Documentation
  • Coverage
  • 100%
    3 out of 3 items documented1 out of 2 items with examples
  • Size
  • Source code size: 3.66 kB This is the summed size of all the files inside the crates.io package for this release.
  • Documentation size: 1.08 MB This is the summed size of all files generated by rustdoc for all configured targets
  • Links
  • Homepage
  • Forestryks/expect_with
    1 0 0
  • crates.io
  • Dependencies
  • Versions
  • Owners
  • Forestryks

expect_with

Crates.io Documentation

Adds expect_with() for Option<T> and Result<T, E> where E is Debug (all std types that has expect method).

This method functions exactly the same as except() but evaluates error message only when actual error occurred.

Example

fn some_heavy_function() -> String {
    return String::from("42");
}

let result: Result<(), String> = Err(String::from("some error"));
result.expect_with(|| format!("error {}", some_heavy_function()));

Motivation

Using expect has one major drawback. It will calculate it's argument every time. Even if no error occurred. This can be really slow if expect is called frequently and evaluating error message envolves some computing (even simple format can be awfully slow). expect_with removes this overhead by accepting lambda, which will be executed to get error message only when needed.