Backslashes are doubling up

When I was trying to make a list of all 8 bit escape codes, (in the format \xbe), I discovered an issue that I could not resolve. When there should be only one backslash, there are two. The code is as follows:

fn make_lit() -> [String; 256] {
  const ARRAY_REPEAT_VALUE: std::string::String = String::new();
  let mut array: [String; 256] = [ARRAY_REPEAT_VALUE; 256];
  for i in 0..=255 as u8 {
    array[i as usize] = format!("\x5cx{:x}", i);
  }
  array
}

The output sample when the array is printed:

..."\\x1f", "\\x20", "\\x21", "\\x22", "\\x23", "\\x24", "\\x25", "\\x26", "\\x27", "\\x28", "\\x29", "\\x2a"...

What the output should look like:

..."\x1f", "\x20", "\x21", "\x22", "\x23", "\x24", "\x25", "\x26", "\x27", "\x28", "\x29", "\x2a"...

I have tried everything that I could think of and the problem is still not resolved. What is wrong and how can I fix it?

How are you printing it? If you use the Debug format like "{array:?}", then yes it is expected that each literal backslash in the string will be escaped itself. You could have also written your format string that way, with "\\" instead of "\x5c", but it means the same thing.

If you print with a normal Display format, the backslash should come through directly.
(The array won't implement Display, but you can print each String in the array yourself.)

You are Debug-printing the array, and it's Debug-printing the Strings, which escapes out the \. If you Display-print the Strings in the array, you will see that there's only one \. Specifically, instead of:

println!("{:?}", array);

use

println!("{}", array.join(", "));

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.