Search code examples
stringrustnewlinerawstring

Include newline in one-line raw string literal?


Constructing a string for bulk posting for the purposes of Elasticsearch, I need to conform to a particular newline formatting. A raw string literal like this does the job:

    let json = format!(r#"{{"index":{{"_id":"{}"}}}}
{}
"#, *num, self.ldoc_texts[sequence_type]);
    self.bulk_post_str.push_str(&json);

Lines 2 and 3 above are deliberately written with no indent in order not to introduce spurious spaces at the start of the line.

Is there any way to write this on the same line?

let json = format!(r#"{{"index":{{"_id":"{}"}}}}\n{}\n"#, *num, self.ldoc_texts[sequence_type]);
self.bulk_post_str.push_str(&json);

The above doesn't work: the literal sequence "\n" is found in the resulting string, instead of newlines.


Solution

  • You can use concat! to stick raw and regular literals together.

    print!(concat!(r#"This is a "raw" literal"#, "\n", r#"continued after "#, "\n"))