In Rust, multi-line strings can be written using raw string literals. Raw strings start with r#" and end with "#. If the string content contains " characters, you can add more # characters between r#" and "# to avoid conflicts.
This approach is ideal for writing strings that contain multiple lines or special characters, as it eliminates the need for escape characters. Here is an example:
rustfn main() { let multiline_string = r#"这是一个 多行 字符串"#; println!("{}", multiline_string); }
In this example, multiline_string holds a three-line string, with actual newline characters separating each line. The advantage of this method is high readability and ease of maintenance.
If you need to include " characters within the string, you can construct the raw string with more # characters, as shown below:
rustfn main() { let complex_string = r##"这个字符串包含特殊字符 " 和 # "##; println!("{}", complex_string); }
In this example, two # characters are used, allowing the string to contain " and # without escape characters. This approach is particularly useful when handling code or configuration files.