Function rust_examples::errors::explained_div[][src]

pub fn explained_div(num: i32, d: &str) -> Result<i32, String>
Expand description

This version of division is somewhat artificial but demonstrates another error context, the Result.

Result is like an Option as it represents an error effect but with the error case being an explicit type (i.e. more informative than plain None). Note that it is also modeled as a Monad.

In this example we get the divisor d as a string slice so we have to parse it first. Therefore there can be three resulting cases:

  1. a Ok result when parsing succeeds and d is non-zer
  2. an Err indicating that d was zero
  3. finally a different Err when parsing fails

Note that here we use simple String to differentiate the error cases but once would typically use custom enum with errors as variants.