Function mycelium_util::fmt::opt

source ·
pub const fn opt<T>(value: &Option<T>) -> FmtOption<'_, T>
Expand description

Borrows an Option as a FmtOption that formats the inner value if the Option is Some, or emits a customizable string if the Option is None.

§Examples

Formatting a Some value emits that value’s Debug and Display output:

use mycelium_util::fmt;

let value = Some("hello world");
let debug = format!("{:?}", fmt::opt(&value));
assert_eq!(debug, "\"hello world\"");

let display = format!("{}", fmt::opt(&value));
assert_eq!(display, "hello world");

Formatting a None value generates no text by default:

use mycelium_util::fmt;

let value: Option<&str> = None;
let debug = format!("{:?}", fmt::opt(&value));
assert_eq!(debug, "");

let display = format!("{}", fmt::opt(&value));
assert_eq!(display, "");

The or_else method can be used to customize the text that is emitted when the value is None:

use mycelium_util::fmt;
use core::ptr::NonNull;

let value: Option<NonNull<u8>> = None;
let debug = format!("{:?}", fmt::opt(&value).or_else("null"));
assert_eq!(debug, "null");