In the nightly Rust it is no longer possible to designate a string literal as String with a "~" character.
In C++, for example, I'm using user-defined literals to concatenate string literals without the crust of mentioning std::string
every time:
inline std::string operator"" _s (const char* str, size_t size) {return std::string (str, size);}
foo ("Hello, "_s + "world!");
Is there a similar feature existing or planned in Rust to make string literal concatenation less painful than String::from_str ("Hello, ") + "world!"
?
If you literally (hah) have string literals, you can use the concat!
macro:
let lit = concat!("Hello, ", "world!")
You can natively split strings over several lines:
let lit = "Hello, \
World";
The \
consumes all following whitespace, including the leading spaces on the next line; omitting the \
will include the string data "verbatim", with newlines and leading spaces etc.
You can add a &str
to a String
:
let s = "foo".to_string() + "bar" + "baz";
You could use push_str
iteratively:
let mut s = "foo".to_string();
s.push_str("bar");
s.push_str("baz");
You could use SliceConcatExt::concat
:
let s = ["foo", "bar", "baz"].concat();
If all else fails, you can define a macro to do exactly what you want.
See also:
- How to concatenate static strings in Rust
- What is the syntax for a multiline string literal?
- How do I concatenate strings?
You can use the format!
macro. It is more readable, more translation-friendly, more efficient, and more powerful (you can concatenate more than just strings, just like C++'s ostringstream
). It is also completely type-safe.
format!("Hello, {}", "world!")
You can also use named arguments to improve readability.
format!("hello, {who}", who = "world")
The full formatting syntax is described in std::fmt
.
Rust does not have user-defined literals. I think adding such a feature is backward-compatible, so maybe this feature will be added after Rust 1.0.
You can concatenate str
literals without using String
with the concat!
macro:
let input = concat!("Hello", ' ', "world");
To make it a string, specify the destination type and use into
:
let input: String = concat!("Hello", ' ', "world").into();
Full program:
fn main() {
let input: String = concat!("Hello", ' ', "world").into();
println!("{}", input); // Output: Hello world
}