Search code examples
stringrustnewlineheredocrawstring

In Rust, is there a way to make literal newlines in r###"..."### using Windows convention?


I'm using Rust on Windows and I found

r###"abc
def"###

results in a string abc\ndef. Is there an easy way to make it abc\r\ndef? Or must I do the replacement manually?


Solution

  • The Rust compiler converts all CRLF sequences to LF when reading source files since 2019 (see merge request, issue) and there is no way to change this behavior.

    What you can do:

    1. Use .replace("\n", "\r\n") at runtime to create a new String with CRLF line terminators.
    2. Use regular instead of raw string literals and end your lines with \r, e.g.
      "abc\r
      def"
      
    3. Use the std::include_str!() macro to include a file in UTF-8 format which contains the text with CRLF line terminators.