Sub topic 3
String literals, escapes, and raw strings
This chapter assumes you know basic Rust syntax, how println! works, and the difference between &str and String from the first chapter.
What a literal is
A string literal such as "hello" has the type &'static str. The compiler stores its bytes in the program binary, and the reference is valid for the whole run. Nothing is allocated at runtime. To get an owned, growable String, you convert it, for example with String::from.
Escape sequences
Inside a normal literal, a backslash starts an escape sequence.
| Escape | Meaning |
|---|---|
| `\n`, `\r`, `\t` | Newline, carriage return, tab |
| `\\` | A backslash |
| `\"` | A double quote |
| `\'` | A single quote (optional in strings) |
| `\0` | The NUL character |
| `\x41` | A character by hex value, limited to `\x00` through `\x7F` |
| `\u{1F980}` | Any Unicode scalar value, 1 to 6 hex digits |
fn main() {
println!("tab:\tend");
println!("quote: \"hi\"");
println!("backslash: \\");
println!("ASCII: \x41");
println!("crab: \u{1F980}");
}Note that \xFF is a compile error in a str literal. Values above \x7F are not valid single-byte UTF-8, so use \u{FF} instead.
Multi-line literals
A literal can span several lines. The newline and any indentation inside the quotes become part of the string. If you end a line with a backslash, the compiler drops the newline and all leading whitespace on the next line.
fn main() {
let a = "line one
line two";
let b = "one \
two";
println!("{a}");
println!("{b}");
}The first literal contains a real newline. The second is the single line one two. Use the backslash form to wrap long messages in source code without changing their content.
Raw strings
A raw string starts with r and does not process escapes. This is useful for Windows paths, regular expressions, and embedded JSON.
fn main() {
let path = r"C:\Users\ferris\notes.txt";
let json = r#"{"name": "Ferris"}"#;
let tricky = r##"She said "#1" loudly"##;
println!("{path}");
println!("{json}");
println!("{tricky}");
}A plain r"..." ends at the first ". To include quotes, add # characters after the r. The string then ends only at a quote followed by the same number of # characters. Pick a count that does not appear inside your text.
Byte string literals
Prefixing a literal with b gives a byte string. Its type is &[u8; N], not &str. Only ASCII characters and \x escapes are allowed.
fn main() {
let bytes: &[u8; 3] = b"abc";
println!("{:?}", bytes);
}You will meet these when working with binary protocols and file formats.
Common errors
- Using
\xabove 7F in astr. Use\u{...}instead. - Forgetting that raw strings ignore escapes.
r"a\nb"is four characters, not a line break. - Unexpected indentation. A multi-line literal keeps its leading spaces unless you end the line with
\. - Braces in format strings. The format string passed to
println!is itself a literal, and{and}are special there. Write{{and}}for literal braces. A raw string does not change this, soprintln!(r#"{{"a": 1}}"#)is correct.
Exercise
Write a literal that holds the text say "hi" \o/ exactly as shown, using a raw string. What is the shortest valid form?
Show answer
r#"say "hi" \o/"#. The text contains double quotes, so a bare r"..." would end early. One # on each side is enough because the text never contains "#.