[−][src]Macro lazy_format::semi_lazy_format
Lazily format something, but eagerly evaluate the arguments ahead of time.
This macro is essentially the same as
format!
, except that
instead of formatting its arguments to a string, it evaluates them and
captures them in an opaque struct, which can be formatted later. This allows
you to build up formatting operations without any extra allocations or
formatting calls.
The return value of this macro is left deliberately unspecified and
undocumented. The most important this about it is its
Display
implementation, which executes the deferred formatting operation. It
also provides Clone
and Copy
if those traits are implementated in all
of the evaluated formatting arguments.
Unlike lazy_format
, this macro is partially lazy, in that it evaluates
its argument expressions and stores the values to be formatted later. This
is often more convenient, especially if the formatted values are simple
data types like integers and &str
. This can also make using the value
easier, as its less likely to capture locally scoped variable or references
and therefore have lifetime issues.
use std::fmt::Display; use std::mem::{size_of_val, size_of}; use lazy_format::semi_lazy_format; fn get_value() -> usize { 1024 } fn get_formatted() -> impl Display { semi_lazy_format!("value: {v}, again: {v}", v = get_value()) } let result = get_formatted(); // At this point, get_value was called, and `result` stores just the // usize return value. No allocations have been performed yet. let result_str = result.to_string(); assert_eq!(result_str, "value: 1024, again: 1024"); assert_eq!(size_of_val(&result), size_of::<usize>());