为什么多行字符串在开头跳过预期的空格? 使用索引

问题描述

我有一些带有预期空格的多行字符串。对于其中一些,删除了一些空格:

const WORKING: &str = "\
┌─┬┐
│ ││
╞═╪╡
│ ││
├─┼┤
├─┼┤
│ ││
└─┴┘
";

const NON_WORKING: &str = "\
  ╷ 
  │ 
╶─┼╴
  │ 
╶─┼╴
╶─┼╴
  │ 
  ╵ 
";

pub fn main() {
    println!("{}",WORKING);
    println!("{}",NON_WORKING);
}

删除了非工作行开头的一些空格。打印:

╷ 
  │ 
╶─┼╴
  │ 
╶─┼╴
╶─┼╴
  │ 
  ╵ 

我认为它必须处理\的使用但我不知道如何解决它而不在"之后开始行

Playground

解决方法

我自己没有尝试过,但我听说 the indoc crate 旨在帮助编写包含缩进的多行字符串文字。它从所有行中均等地删除前导空格,而不是 \ 独立地从每行中删除前导空格的行为。

使用索引

use indoc::indoc;

fn main() {
    let testing = indoc! {"
        def hello():
            print('Hello,world!')

        hello()
    "};
    let expected = "def hello():\n    print('Hello,world!')\n\nhello()\n";
    assert_eq!(testing,expected);
}
,

Rust 会自动删除预期的空格,因为长字符串通常像这样分成多行,空格仅用于格式化。

您可以使用 raw strings 禁用此行为。请注意开头和结尾处的额外 r 和自定义分隔符 #

const NON_WORKING: &str = r#"
  ╷ 
  │ 
╶─┼╴
  │ 
╶─┼╴
╶─┼╴
  │ 
  ╵ 
"#;
,

我最终使用了普通的 str 并删除了最初的 \n

let WORKING: &str ="
 ── 
    
 ── 
    
 ── 
 ── 
    
 ── ".trim_start_matches("\n")