How to create a multiline string in Rust
Created
Modified
Using triple-quotes
A string literal is a sequence of any Unicode characters enclosed within two U+0022 (double-quote) characters, with the exception of U+0022 itself, which must be escaped by a preceding U+005C character (\). The following example:
fn main() {
// Backslash line brea
let s = "Apple \
Google \
Twitter";
println!("{}", s);
// unnecessary spaces
let s1 = "Apple
Google
Twitter";
println!("{}", s1);
}
Apple Google Twitter Apple Google Twitter
Using Raw string literals
Raw string literals do not process any escapes. They start with the character U+0072 (r), followed by zero or more of the character U+0023 (#) and a U+0022 (double-quote) character. For example,
fn main() {
// Raw string literals
let s = r#"Apple
Google
Twitter"#;
println!("{}", s);
}
Apple Google Twitter
you can denote an arbitrary number of hashes as a delimiter:
fn main() {
// Raw string literals
let s = r###"Apple
Google ##"#
Twitter"###;
println!("{}", s);
}
Apple Google ##"# Twitter
Using concat Method
You can use the concat! macro. It concatenates string literals at compile time. For example,
fn main() {
// concat
let s = concat!(
"Apple",
10,
true
);
println!("{}", s);
}
Apple10btrue