多行字符串文字的语法是什么?

What is the syntax for a multiline string literal?

我很难搞清楚字符串语法在 Rust 中是如何工作的。具体来说,我正在尝试弄清楚如何制作多行字符串。

所有字符串文字都可以分成几行;例如:

let string = "line one
line two";

是两行字符串,和"line one\nline two"一样(当然也可以直接用\n换行转义)。如果您出于格式化原因希望将字符串跨多行分开,您可以使用 \; 转义换行符和前导空格;例如:

let string = "one line \
    written over \
    several";

"one line written over several"相同。

如果你想在字符串中换行,你可以在 \:

之前添加它们
let string = "multiple\n\
              lines\n\
              with\n\
              indentation";

"multiple\nlines\nwith\nindentation";一样

如果您想做一些更长的事情,可能包括也可能不包括引号、反斜杠等,请使用 raw string literal notation:

let shader = r#"
    #version 330

    in vec4 v_color;
    out vec4 color;

    void main() {
        color = v_color;
    };
"#;

如果您的字符串中有双引号和散列符号序列,您可以将任意数量的散列表示为分隔符:

let crazy_raw_string = r###"
    My fingers #"
    can#"#t stop "#"" hitting
    hash##"#
"###;

输出:


    #version 330

    in vec4 v_color;
    out vec4 color;

    void main() {
        color = v_color;
    };

Playground link

is correct but if the indentation bothers you, consider using Indoc 这是用于缩进多行字符串的过程宏。它代表“缩进文档”。它提供了一个名为 indoc!() 的宏,它采用多行字符串文字并取消缩进,因此最左边的非 space 字符位于第一列。

let s = indoc! {"
    line one
    line two
"};

结果是"line one\nline two\n"

Whitespace 相对于文档中最左边的非 space 字符保留,因此下面的第二行相对于第一行缩进了 3 spaces:

let s = indoc! {"
    line one
       line two
"};

结果是"line one\n line two\n"

如果您想在代码中缩进多行文本:

let s = "first line\n\
    second line\n\
    third line";

println!("Multiline text goes next:\n{}", s);

结果如下:

Multiline text goes next:
first line
second line
third line

如果你想在不使用外部板条箱的情况下对带有换行符的多行字符串中的 space 进行精细控制,你可以执行以下操作。示例取自我自己的项目。

impl Display for OCPRecData {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "OCPRecData {{\n\
            \x20   msg: {:?}\n\
            \x20   device_name: {:?}\n\
            \x20   parent_device_name: {:?}\n\
        }}", self.msg, self.device_name, self.parent_device_name)
    }
}

结果

OCPRecData {
    msg: Some("Hello World")
    device_name: None
    parent_device_name: None
}
  • \n\ 在每个代码行末尾创建一个换行符并在这行代码中进一步丢弃 spaces
  • \x20(十六进制;十进制为 32)是一个 ASCII space 并且是第一个 space 的指示符,要保留在字符串的这一行
  • \x20\x20\x20\x20\x20 效果一样