Newline in source code files and strings

If we want to create a complex string (that is, we need to use the original string, and cannot use the escape character \r\n) and need "CRLF" as the newline character, it does not work to save the source code file as "CRLF". The string always uses "LF" as the newline character

The code is as follows:

fn main() {
    let json_str = r#"{
    //Expected output:
    //"{\r\n    \"name\":\"zhang_san\",\r\n    \"age\":\"13\"\r\n}"
    //Actual output:
    //"{\n    \"name\":\"zhang_san\",\n    \"age\":\"13\"\n}"

Does the compiler need to make changes, such as: let the string follow the newline character of the source code, or add an error prompt“ error:couldn't read src\ : stream did not contain valid LF ", just like" error: couldn't read src\ : stream did not contain valid UTF-8".

The above is machine translation, my English is not good

That's an unfortunate requirement. I think you can write a macro which inserts CRLF into the strings.

1 Like

Yes, it is actually very simple to achieve the result. But the CRLF string becomes LF when written into the code, which may be a bit forced for me. Maybe it is my own problem. Thank you for your reply.

You can use include_str! if you need line endings preserved.

1 Like

This is documented here.


Forgive me for another question, why does it do this? What's the benefit of doing this?

In document:

Both byte sequences are normally translated to U+000A

Consistency, so you get the same result no matter where you compile the code.

1 Like

So why not convert to "\r\n"?(This is my last question. I'm stupid.`(>﹏<)′)

Because they had to choose one convention and chose the simpler one (\n vs \r\n).

1 Like

all right.╮(╯-╰)╭