Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wrap a raw string literal without inserting newlines into the raw string?

I have a raw string literal which is very long. Is it possible to split this across multiple lines without adding newline characters to the string?

file.write(r#"This is an example of a line which is well over 100 characters in length. Id like to know if its possible to wrap it! Now some characters to justify using a raw string \foo\bar\baz :)"#)

In Python and C for example, you can simply write this as multiple string literals.

# "some string"
(r"some "
 r"string")

Is it possible to do something similar in Rust?

like image 778
ideasman42 Avatar asked Aug 19 '16 00:08

ideasman42


People also ask

How do you close a string literal in Python?

String quotes can be escaped with a backslash, but the backslash remains in the string; for example, r"\"" is a valid string literal consisting of two characters: a backslash and a double quote; r"\" is not a valid string literal (even a raw string cannot end in an odd number of backslashes).

What does \r mean in a string?

The r means that the string is to be treated as a raw string, which means all escape codes will be ignored. For an example: '\n' will be treated as a newline character, while r'\n' will be treated as the characters \ followed by n .

What characters must enclose a string literal?

A "string literal" is a sequence of characters from the source character set enclosed in double quotation marks (" "). String literals are used to represent a sequence of characters which, taken together, form a null-terminated string.

What is a raw string literal?

Raw String Literal in C++ A Literal is a constant variable whose value does not change during the lifetime of the program. Whereas, a raw string literal is a string in which the escape characters like ' \n, \t, or \” ' of C++ are not processed. Hence, a raw string literal that starts with R”( and ends in )”.


1 Answers

While raw string literals don't support this, it can be achieved using the concat! macro:

let a = concat!(
    r#"some very "#,
    r#"long string "#,
    r#"split over lines"#);

let b = r#"some very long string split over lines"#;
assert_eq!(a, b);
like image 101
paholg Avatar answered Sep 30 '22 17:09

paholg