Multi-line string in Rust with preserved leading whitespace

You can start the line you want to indent with a ASCII quoted space \x20 or an Unicode quoted space \u{20}.

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

You just need to quote the first space.

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

No it's not possible (v1.3 and probably for a long time).

However, usually multi-line string literals that need to be human-readable are some sort of constant descriptions, like the usage string for a CLI program. You often see those things indented like this:

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

Usage:
  ...
";

Which is ok I guess. If you have a lot of those strings or a really big one, you could use include_str!.


It is not supported by the language as of Rust 1.7 but Indoc is a procedural macro that does what you want. It stands for "indented document." It provides a macro called indoc!() that takes a multiline string literal and un-indents it so the leftmost non-space character is in the first column.

let some_string = indoc! {"
    First line.
     Second line, with leading space."
};

It works for raw string literals as well.

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

The result in both cases is "First line\n Second line, with leading space."