Multiline string in Rust with leading spaces retained

Some languages ​​can write something like this:

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

That is, a multi-line string in which all the leading space is deleted to a point, but no further. This can be mimicked in Rust by writing:

 let some_string = "First line.\n \ Second line, with leading space."; 

However, this loses the benefit of approaching the actual result. Is there a way in Rust to write something like an example pseudo-code, while preserving (some) leading spaces?

+5
source share
2 answers

No, this is not possible ( v1.3 and probably for a long time).

However, as a rule, multi-line string literals, which should be human-readable, are some kind of constant descriptions, such as the use string for the CLI program. You often see things that fall back like this:

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

What I think. If you have a lot of such lines or really big, you can use include_str! .

+4
source

It is not supported by the language with Rust 1.7, but Indoc is a procedural macro that does what you want. This means "indented document." It provides a macro called indoc!() , Which takes a multi-line string literal and discards it so that the left-most non-spatial character is in the first column.

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

It also works for string literals.

 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."

+3
source

Source: https://habr.com/ru/post/1234491/


All Articles