Rust中的多行字符串,保留前导空格

时间:2015-10-25 20:56:14

标签: rust whitespace pretty-print

在某些语言中,可以编写类似的东西:

val some_string =
  """First line.
    | Second line, with leading space."""

也就是说,一个多行字符串,其中所有前导空格都被删除到一个点,但没有进一步。这可以通过写:

在Rust中模仿
let some_string = 
    "First line.\n \
     Second line, with leading space.";

但是,这会失去接近实际输出的好处。有没有办法在Rust中编写类似于伪代码的示例,保留(某些)前导空格?

3 个答案:

答案 0 :(得分:6)

不可能(v1.3并且可能很长时间)。

但是,通常需要人类可读的多行字符串文字是某种常量描述,如CLI程序的用法字符串。你经常看到那些缩进的东西:

const USAGE: &'static str = "
Naval Fate.

Usage:
  ...
";

我猜这是好的。如果你有很多这些字符串或非常大的字符串,你可以使用include_str!

答案 1 :(得分:6)

Rust 1.7的语言不支持它,但Indoc是一个程序宏,它可以满足您的需求。它代表“缩进文档”。它提供了一个名为indoc!()的宏,它接受多行字符串文字并取消缩进,使最左边的非空格字符位于第一列。

let some_string = indoc!("
    First line.
     Second line, with leading space.");

它也适用于原始字符串文字。

let some_string = indoc!(r#"
    First line.
     Second line, with leading space."#);

两种情况下的结果都是"First line\n Second line, with leading space."

答案 2 :(得分:1)

您可以使用ASCII引号空格\x20或Unicode引号空格\u{20}开始要缩进的行。

let some_string = 
    "First line.\n\
     \x20Second line, with leading space.\n\
     \u{20}Third line, with leading space.";

您只需要引用第一个空格。

let some_string = 
    "First line.\n\
     \x20 Second line, with two leading spaces.\n\
     \u{20} Third line, with two leading spaces.";