How do I write a multi-line string in Rust?

后端 未结 5 1017
长情又很酷
长情又很酷 2021-02-02 06:06

Is it possible to write something like:

fn main() {
    let my_string: &str = \"Testing for new lines \\
                           might work like this?\";
         


        
5条回答
  •  闹比i
    闹比i (楼主)
    2021-02-02 06:48

    There are two ways of writing multi-line strings in Rust that have different results. You should choose between them with care depending on what you are trying to accomplish.

    Method 1: Dangling whitespace

    If a string starting with " contains a literal line break, the Rust compiler will "gobble up" all whitespace between the last non-whitespace character of the line and the first non-whitespace character of the next line, and replace them with a single .

    Example:

    fn test() {
        println!("{}", "hello  
        world");
    }
    

    No matter how many literal (blank space) characters (zero or a hundred) appear after hello, the output of the above will always be hello world.

    Method 2: Backslash line break

    This is the exact opposite. In this mode, all the whitespace before a literal \ on the first line is preserved, and all the subsequent whitespace on the next line is also preserved.

    Example:

    fn test() {
        println!("{}", "hello  \
        world");
    }
    

    In this example, the output is hello world.

    Additionally, as mentioned in another answer, Rust has "raw literal" strings, but they do not enter into this discussion as in Rust (unlike some other languages that need to resort to raw strings for this) supports literal line breaks in quoted content without restrictions, as we can see above.

提交回复
热议问题