Sub topic 3
String literals, escapes, and raw strings
This chapter covers the text you type directly into Rust source code. It assumes you know basic Rust syntax and have met &str and String as the borrowed and owned string types. It also assumes you can read a println! call. Later chapters cover creating and changing String values.
What a string literal is
A string literal is text between double quotes in your source code. Its type is &'static str. The bytes are stored in the compiled program's read-only data, and the literal gives you a shared reference to them. Nothing is allocated on the heap when the program runs, and the reference is valid for the whole program (the 'static lifetime).
fn main() {
let s: &'static str = "hello";
println!("{s} has {} bytes", s.len());
}Because the data is read-only, you cannot change a literal. To get something you can edit, copy it into a String with String::from or .to_string(). That is why literals are the usual starting point and String is the usual working type.
Every literal is valid UTF-8, and the compiler checks this when it parses your file. Any Unicode character can appear directly in a literal, so "héllo" and "日本語" need no special syntax.
Escape sequences
Some characters are hard to type or would confuse the parser. A backslash starts an escape sequence that stands for one of them.
| Escape | Meaning |
|---|---|
| `\n` | Newline (line feed) |
| `\r` | Carriage return |
| `\t` | Tab |
| `\\` | A backslash |
| `\"` | A double quote |
| `\'` | A single quote (allowed, but rarely needed in strings) |
| `\0` | The NUL character (code point 0) |
| `\x41` | The ASCII character with that two-digit hex value, from `\x00` to `\x7F` |
| `\u{2764}` | The Unicode scalar value with that hex value, one to six digits |
fn main() {
println!("tab:\there");
println!("quote: \"hi\"");
println!("backslash: \\");
println!("A is \x41");
println!("heart: \u{2764}");
println!("e acute: \u{e9}");
}Two rules produce most beginner errors.
\xstops at7Fin astr. Astrmust be valid UTF-8, and a lone byte such as0xE9is not a complete character. The compiler rejects"\xE9"with an "out of range hex escape" error. Write"\u{e9}"instead.- Unknown escapes are errors.
"\d"does not compile, with "unknown character escape". This catches people who paste in a regular expression such as\d+. Double the backslash ("\\d+") or use a raw string, covered below.
The \u{...} escape takes a Unicode scalar value. That is any code point except the surrogate range D800 to DFFF, and it must be at most 10FFFF. Values outside that range are compile errors.
Multi-line literals and line continuation
A literal can span several lines. The newline and any indentation you type become part of the string.
A backslash at the end of a line works differently. It removes the newline and all whitespace at the start of the next line. This lets you wrap long text in source code without changing the string.
fn main() {
let wrapped = "one \
two";
let literal = "one
two";
println!("{wrapped}");
println!("{literal:?}");
}The first string is "one two". The second contains a newline followed by the indentation spaces, which {:?} shows as \n and the spaces. Note the space before the backslash in "one \. Without it, you would get "onetwo".
If your source file uses Windows line endings (CRLF), the compiler converts them to \n inside literals. The string is the same on every platform.
Raw string literals
Escapes get in the way when the text has many backslashes or quotes, such as file paths, regular expressions, or JSON. A raw string treats every character literally. It starts with r" and ends at the next ".
fn main() {
let path = r"C:\Users\ferris\notes.txt";
let pattern = r"\d+\.\d+";
println!("{path}");
println!("{pattern}");
}Inside r"...", \n is two characters, a backslash and an n. The one thing a plain raw string cannot hold is a double quote, because that ends it.
To include quotes, add hash marks on both ends. The literal then ends only at a quote followed by the same number of hashes. You can use as many hashes as you need.
fn main() {
let json = r#"{"name": "Ferris"}"#;
let tricky = r##"He said "#hello#" to me"##;
println!("{json}");
println!("{tricky}");
}In tricky, the text contains "#. A single-hash raw string would end at that point, so the literal uses two hashes. If you get a confusing "unterminated raw string" error, add one more hash to both ends.
Raw strings can also span lines. As with ordinary literals, newlines and indentation are kept, and line continuation does not work because backslashes are not special.
fn main() {
let help = r#"Usage:
tool --name "value"
tool --help"#;
println!("{help}");
}Choosing a literal form
The diagram shows how to pick a form for a given piece of text.
Byte string literals
A byte string literal has a b prefix. Its type is not &str. It is a reference to an array of bytes, &'static [u8; N], where N is the length.
fn main() {
let bytes: &[u8; 5] = b"hello";
let raw = b"\xff\x00";
println!("{:?} {:?}", bytes, raw);
println!("{}", bytes.len());
let s = std::str::from_utf8(bytes).unwrap();
println!("{s}");
}Byte strings accept only ASCII characters and escapes. In exchange, \x can go up to \xFF, because the result need not be valid UTF-8. This makes them suited to binary protocols, file signatures, and test data. You can combine the prefixes as br"..." and br#"..."# for raw byte strings.
To treat bytes as text, validate them first with std::str::from_utf8, as above. A later chapter covers handling invalid input.
There is also a b'a' byte literal for a single byte of type u8. A plain 'a' is a char, which is four bytes wide and holds one Unicode scalar value. Single quotes and double quotes are never interchangeable in Rust.
C string literals
Since Rust 1.77, a c"..." literal produces a &'static CStr. The compiler appends the terminating NUL byte for you. It rejects an interior \0, because that would end the string early for C code. This is useful for foreign function interfaces and is covered in the final chapter on OsString, Path, and CString.
use std::ffi::CStr;
fn main() {
let c: &CStr = c"hello";
println!("{}", c.to_bytes().len());
println!("{}", c.to_bytes_with_nul().len());
}The first line prints 5 and the second prints 6, which includes the NUL.
Literals and format strings
The first argument to println!, format!, and write! must be a string literal, because the compiler checks it at build time. In those literals, curly braces are special. To print a brace, double it.
fn main() {
let n = 3;
println!("{{n}} is {n}");
println!(r"C:\temp\{n}");
}This prints {n} is 3 and then C:\temp\3. The second line shows that raw strings work as format strings. Escape handling and brace handling are separate steps: the compiler first reads the literal, then reads the braces in the result. A raw string does not turn off {}, so you still write {{ to print a literal brace.
You cannot pass a String variable as the format string, as in println!(my_string). That is a compile error. Write println!("{my_string}") instead.
Related compile-time helpers
concat!("a", "b")joins literals into one&'static strat compile time.include_str!("data.txt")reads a file at compile time and gives you its contents as a&'static str. The path is relative to the source file containing the macro, and the file must be valid UTF-8.include_bytes!("data.bin")does the same for raw bytes and gives a&'static [u8; N].
These embed data in the binary, so nothing is read from disk when the program runs.
Common mistakes
- Using
\x80or higher in astr. Use\u{...}for non-ASCII characters, or a byte string if you really need bytes. - Writing regular expressions or Windows paths with single backslashes. Use a raw string.
- Forgetting the hashes. A raw string containing
"needsr#"..."#at least. - Expecting
b"abc"to be a&str. It is&[u8; 3]. Passing it to a function that takes&stris a type error. - Using single quotes for a string.
'ab'is a compile error, because single quotes hold exactly one character. - Assuming leading indentation disappears in multi-line literals. It is kept unless you end the line with a backslash.
Exercise
A program needs the Windows path C:\new\table.txt as a string. Show a literal that stores it correctly, and say what an ordinary literal "C:\new\table.txt" would produce instead.
Show answer
Use r"C:\new\table.txt". In an ordinary literal, \n becomes a newline and \t becomes a tab, so the string would contain the text "C:", a newline, "ew", a tab, "able.txt". (The ordinary form would need doubled backslashes: "C:\\new\\table.txt".)
Exercise
What are the types of "abc", b"abc", 'a', and b'a', and why does "\xE9" fail to compile while b"\xE9" does not?
Show answer
"abc" is &'static str, b"abc" is &'static [u8; 3], 'a' is char, and b'a' is u8. A str must be valid UTF-8, and a single byte 0xE9 is not a complete character, so \x escapes in a str are limited to \x7F. A byte string holds arbitrary bytes, so \xE9 is allowed there.