Below is one possible way to move that “give-me-the-first-arg-or-early-return” snippet into a small macro_rules! macro.
(Feel free to tweak the name or style to suit your code base.)
rust
// Put this in the same module (or a prelude) so the macro is visible.
macro_rules! first_arg_or_return_empty {
($args:expr) => {{
if $args.is_empty() {
// ⇨ This `return` will still return from whatever function / closure
// you expand the macro in, because macros are expanded *in place*.
return String::new();
} else {
// `&` keeps the reference semantics you had
&$args[0]
}
}};
}
and then your original code becomes
rust
let lower: ContextFunction = Box::new(|args| {
// 👇 👇 just call the macro
let s = first_arg_or_return_empty!(args);
s.to_lowercase()
});
Why it works
macro_rules! is token-based, so return inside the macro still “jumps out” of the
surrounding function / closure where the macro is expanded.
The macro evaluates to an expression (&$args[0]) when it doesn’t early-return,
letting you bind it to let s = …;.
Both branches yield the same type: &String (or &str if your args is a
Vec<String> and you prefer "" instead of String::new() for the empty case).
Alternatives / tweaks
• If you don’t want an early return inside the macro, you can return a default
string slice instead: