Rust String Literals
A string literal is text written directly in code, inside double quotes. Escapes give special characters a spelling inside a literal.
Escapes inside normal text
A backslash gives a character a special meaning: \n is a new line and \t is a tab. (\\ writes one plain backslash.)
let s = "one\ntwo\tthree";
println!("{s}");Write a character by its number
\x takes two hex digits. \u{...} takes a Unicode number:
let letter = '\x52';
let symbol = "\u{211D}";
println!("{letter} {symbol}");Raw strings keep every backslash
Put r in front and escapes switch off — each backslash is just a backslash, which suits file paths:
let path = r"C:\new\folder";
println!("{path}");Raw strings with quotes inside
Add # marks around the quotes, and the text may hold plain quotes:
let quote = r#"She said "no escape needed""#;
println!("{quote}");Byte strings and back to text
b"..." gives bytes, printed as numbers. from_utf8 tries to turn bytes back into text. It answers with a Result. The bytes might not be valid UTF-8:
let bytes = b"Rust";
println!("bytes = {:?}", bytes);
println!("text = {:?}", std::str::from_utf8(b"hello"));
println!("bad is ok = {}", std::str::from_utf8(&[255, 254]).is_ok());Example
fn main() {
let hex = "I'm writing \x52\x75\x73\x74!";
println!("{}", hex);
let symbol = "\u{211D}";
println!("symbol = {}", symbol);
let path = r"C:\new\folder";
println!("path = {}", path);
let quote = r#"And then I said: "There is no escape!""#;
println!("{}", quote);
let bytes = b"Rust as bytes";
println!("bytes = {:?}", bytes);
let text = std::str::from_utf8(b"hello");
println!("as text = {:?}", text);
let bad = std::str::from_utf8(&[255, 254]);
println!("bad is ok = {}", bad.is_ok());
}Key points
- Use a byte string b"..." to get bytes.
- You get &[u8], not text.
- It has no {} printing.
- \u escapes are not allowed in it
- A literal puts the exact text in the code: its spelling tells Rust how to read each character.
In this example, the hex escapes spell out letters. \x52 \x75 \x73 \x74 spell R, u, s, t. So the first line prints I'm writing Rust!. The \u{211D} escape prints its symbol. The path is a raw string, so its backslashes stay literal and no new line appears. The quote uses r#"..."# so the inner quotes need no escaping. The byte string prints as a list of numbers. from_utf8 turns the hello bytes into Ok text. The 255, 254 bytes are not valid UTF-8. So bad is ok = false prints.
Note
A normal &str and a byte string can look alike in code.
Only the &str is promised to be valid UTF-8 text.
The byte string is just numbers.
It stays numbers until a check passes.
A check like from_utf8 must pass.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Rust Playground
Exercise
What does a raw string r"..." do to backslashes?