Firstly, I believe the issue is the same as with this: (i.e. not specific to format_args
)
//error[E0716]: temporary value dropped while borrowed
consume(
//----- borrow later used by call
if cond {
&then_block(4)
// ^^^^^^^^^^^^^ creates a temporary which is freed while still in use
} else {
// - temporary value is freed at the end of this statement
&else_block(7)
}
);
I agree that ought to compile, but I have no idea if it could be changed.
Labeled breaks and tuple evaluation do enable a workaround:
macro_rules! if_then_else {
($cond:expr, $then:expr, $otherwise:expr) => {
'if_else: {
(
'yes: {
if $cond { break 'yes }
break 'if_else $otherwise
},
$then
).1
}
}
}
With that my earlier example becomes:
pub fn apples(n: usize) -> String {
format!("There {}!",
if_then_else!(n==0, format_args!("are no ({n}) apples"),
if_then_else!(n==1, format_args!("is just one ({n}) apple"),
if_then_else!(n==2, format_args!("are two ({n}) apples"),
format_args!("are {n} apples")
)))
)
}