Table of Contents

Coding best practice in Rust

There are several ways to implement the same approach in Rust. Here we collect implementation details for different usecases to provide useful examples.

1.1. Get value of an Option<T> or return with error if it is None:

use anyhow::{anyhow, Result};

fn function_1_1() -> Result<()> {
...
    let opt = Some(1);
    let value = opt.ok_or(anyhow!("Error message"))?;
...
}

1.2. Get value of an Option<T> and perform an additional operation on it or return an error if it is None:

use anyhow::{anyhow, Result};
use rust_decimal::Decimal;

fn function_1_2() -> Result<()> {
...
    let opt = Some(1.2);
    let value: Decimal = match opt {
        Some(v) => v.try_into()?,
        None => anyhow::bail!("Error message"),
    };

1.3. Write error into log if a function returning an Err as Result<T>:

use anyhow::{anyhow, Result};
use log;

fn function_returns_result() -> Result<()> {..}

if let Err(e) = function_returns_result() {
    log::debug!("Error: {}", e)
};