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!"
?
Using connect() method connect() method in Rust flattens a slice of type T into a single value of type U and is similar to concat() method. The additional feature in connect() method is that we can specify a string (known as separator) that will be placed between each string of the slice.
The most efficient is to use StringBuilder, like so: StringBuilder sb = new StringBuilder(); sb. Append("string1"); sb.
In summary, use String if you need owned string data (like passing strings to other threads, or building them at runtime), and use &str if you only need a view of a string.
String literals (&str) are used when the value of a string is known at compile time. String literals are a set of characters, which are hardcoded into a variable. For example, let company="Tutorials Point". String literals are found in module std::str. String literals are also known as string slices.
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With