Cannot figure out how to return a string with newlines

What is a good way to build a string from

  • some string literals and
  • some struct fields?
impl MyType{
  pub fn return_a_string(self: Self)->String { 
    let mut out = String::new();
    out.push_str("        (GmmiTextObject");
    out.push_str("          (GmmiObject \"\" 0");
    out.push_str("            MORE TEXT ");
    out.push_str(&; // my data
    out.push_str("\" 0)");   

I call this function in a loop and write it to a text file using write!

        for data in & {
          write!(output, "{:?}\r\n", data.return_a_string());

The problem is:

  • It is all on one line (I tried adding \r\n but it just prints it out)
  • It gets a " in front of each line
"        (GmmiTextObject          (GmmiObject \"\" 0            (Help \"\" \"\" \"\")            (GmmiOptionTable              <SNIP>          (Point 2520 4500) \"EQUIPMENT\" 0)"

Your strings don't end with newlines, hence no newlines will be printed out of the blue.

As for the quotes: {:?} prints a debug representation. You likely meant to use {} instead, which formats the value using Display.

1 Like

Another thing to note is that String implements Write, so in your case you can use the writeln!() macro:

    pub fn return_a_string(self: Self) -> String {
        let mut out = String::new();
        writeln!(out, "        (GmmiTextObject");
        writeln!(out, "          (GmmiObject \"\" 0");
        writeln!(out, "            MORE TEXT ");

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.