macro_rules! concat_str {
(
@pre {$($pre:stmt,)*},
@strname $strname:ident,
@len $($len:expr)?,
@appends {$($appends:expr,)*},
$head:literal $(, $($tail:tt)*)?
) => { ... };
(
@pre {$($pre:stmt,)*},
@strname $strname:ident,
@len $($len:expr)?,
@appends {$($appends:expr,)*},
$head:ident $(, $($tail:tt)*)?
) => { ... };
(
@pre {$($pre:stmt,)*},
@strname $strname:ident,
@len $($len:expr)?,
@appends {$($appends:expr,)*},
$head:expr $(, $($tail:tt)*)?
) => { ... };
(
@pre {$($pre:stmt,)*},
@strname $strname:ident,
@len $len:expr,
@appends {$($appends:expr,)*},
) => { ... };
($($tt:tt)+) => { ... };
}Expand description
Concatenates a sequence of string-like arguments into a new String.
This macro offers high-performance string concatenation by calculating the total
length of all arguments upfront and performing only a single memory allocation.
It serves as a more efficient alternative to repeated use of the + operator or
format! when all arguments are string-based.
§Arguments
The macro accepts a comma-separated list of arguments that can be converted to &str:
- String literals (e.g.,
"hello"). &Stringvariables (e.g.,&my_string).&strslices (e.g.,my_slice).- Expressions that evaluate to a string type (e.g.,
&user.nameor&num.to_string()).
§Panics
The macro itself does not introduce panics. However, expressions passed to it might panic, for example, due to indexing out of bounds.
§Examples
Basic usage:
let s = concat_str!("the quick ", "brown ", "fox");
assert_eq!(s, "the quick brown fox");Mixing literals and variables:
let color = "brown";
let animal = String::from("fox");
let sentence = concat_str!("the quick ", color, " ", &animal, " jumps over...");
assert_eq!(sentence, "the quick brown fox jumps over...");Using expressions:
let num = 42;
let text = concat_str!("The answer is ", &num.to_string(), ".");
assert_eq!(text, "The answer is 42.");