[−][src]Macro lazy_format::semi_lazy_format
Lazily format something by eagerly evaluate the arguments ahead of time, then storing them and formatting them at write 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 thing 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. However, this also limits
semi_lazy_format!
to only supporting plain formatting, rather than the
conditional and looping structures supported by lazy_format!
.
use std::fmt::Display; use std::mem::{size_of_val, size_of}; use lazy_format::semi_lazy_format; fn get_formatted() -> impl Display { let x: isize = 512; let y: isize = 512; semi_lazy_format!("value: {v}, again: {v}", v = (x + y)) } let result = get_formatted(); // At this point, addition expression has been performed. `result` // captures only the result of the expression, rather than the two // operands. assert_eq!(size_of_val(&result), size_of::<isize>()); let result_str = result.to_string(); assert_eq!(result_str, "value: 1024, again: 1024");