有可能写出类似的东西:
fn main() {
let my_string: &str = "Testing for new lines \
might work like this?";
}
Run Code Online (Sandbox Code Playgroud)
Moe*_*ius 33
另一种方法是使用原始字符串文字:
原始字符串文字不处理任何转义.它们以character
U+0072(r)开头,后跟零个或多个characterU+0023(#)和一个U+0022(双引号)字符.原始字符串主体可以包含任何Unicode字符序列,并且仅由另一个U+0022(双引号)字符终止,后跟U+0023在开头U+0022(双引号)字符之前的相同数量的(#)字符.原始字符串体中包含的所有Unicode字符代表它们自己,字符
U+0022(双引号)(除非后跟至少与用于启动原始字符串文字一样多的U+0023(#)字符)或U+005C(\)没有任何特殊含义.字符串文字的示例:
Run Code Online (Sandbox Code Playgroud)"foo"; r"foo"; // foo "\"foo\""; r#""foo""#; // "foo" "foo #\"# bar"; r##"foo #"# bar"##; // foo #"# bar "\x52"; "R"; r"R"; // R "\\x52"; r"\x52"; // \x52
如果您想避免出现换行符和额外空格,可以使用concat!宏。它在编译时连接字符串文字。
let my_string = concat!(
"Testing for new lines ",
"might work like this?",
);
assert_eq!(my_string, "Testing for new lines might work like this?");
Run Code Online (Sandbox Code Playgroud)
Rust 中的每个字符串都是多行字符串。
但是如果您的文本中有缩进,例如:
fn my_func() {
const MY_CONST: &str = "\
Hi!
This is a multiline text!
";
}
Run Code Online (Sandbox Code Playgroud)
你会得到不必要的空间。要删除它们,您可以使用板条箱indoc!中的宏indoc来删除所有缩进: https: //github.com/dtolnay/indoc