-1

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.

cafce25
  • 15,907
  • 4
  • 25
  • 31
mike rodent
  • 14,126
  • 11
  • 103
  • 157
  • Refer to [Rust by example: Strings](https://doc.rust-lang.org/rust-by-example/std/str.html): raw string literals don’t support escapes, so you can use a normal string literal and escape the required characters (newlines, double quotes, etc.) or stick with the multiline raw string literal. If this addresses your question, I can write it as an answer. If not, what did I miss? – jsejcksn Aug 31 '23 at 08:06

2 Answers2

2

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

print!(concat!(r#"This is a "raw" literal"#, "\n", r#"continued after "#, "\n"))
cafce25
  • 15,907
  • 4
  • 25
  • 31
n. m. could be an AI
  • 112,515
  • 14
  • 128
  • 243
1

The options mentioned so far do not seem very readable. I'd go for something that shows the intent more clearly, e.g.

use serde_json::{json, to_string}, std::fmt::Write;

let json = json!({"index": {"_id": *num}});
writeln!(self.bulk_post_str, "{}", to_string(&json).unwrap()).unwrap();
writeln!(self.bulk_post_str, "{}", self.ldoc_texts[sequence_type]).unwrap();

This is a bit more verbose, but I think it's a lot easier to read.

The unwrap()s are a bit unfortunate, but they are all for infallible calls.

Sven Marnach
  • 574,206
  • 118
  • 941
  • 841