display_with

Function display_with 

Source
pub fn display_with(f: impl Fn(&mut Formatter<'_>) -> Result) -> impl Display
Expand description

Helper function to defer formatting to later, without having to allocate a intermediate String

similar to format_args!, but it can be returned by moved values

Source: https://internals.rust-lang.org/t/suggestion-for-helper-for-writing-fmt-debug-impls-with-nested-structure/19477/2

Example:

// instead of `fn nested() -> String`
fn nested() -> impl Display {
  let new_string = String::from("Hello allocated string");
  // instead of `format!("Formatted! {}", new_string)`
  display_with(move |f| write!(f, "Formatted! {}", new_string))
}

println!("No Extra allocation:\n{}", nested());