Sub topic 1
Rust Strings: `str`, `String`, and UTF-8 in Practice
Prerequisites
Assume basic Rust syntax, ownership, borrowing, and familiarity with Option and Result.
Two string types: `&str` and `String`
Rust has two common text types:
stris a dynamically sized sequence of UTF-8 bytes. You usually use it through&str, a borrowed string slice.Stringowns its text. It stores UTF-8 bytes on the heap and can grow or change.
A string literal such as "hello" has type &'static str. Its contents are compiled into the program, so the literal cannot be modified. Use String when your code needs ownership or mutation.
A function that only reads text usually accepts &str:
fn describe(text: &str) {
println!("{text}");
}
fn main() {
let owned = String::from("hello");
describe("literal");
describe(&owned);
}Rust can temporarily view &String as &str through deref coercion.
UTF-8 and what a Rust string really holds
Both str and String must contain valid UTF-8. UTF-8 uses one or more bytes for each Unicode scalar value. Therefore, byte length and character count can differ:
fn main() {
let s = "héllo";
println!("bytes: {}", s.len());
println!("chars: {}", s.chars().count());
}This prints bytes: 6 and chars: 5, because é uses two bytes.
String literals, escapes, and raw strings
Regular literals support escapes such as \n, \", and \\:
fn main() {
let message = "first line\nsecond line";
let pattern = r"C:\temp\file.txt";
println!("{message}");
println!("{pattern}");
}A raw string begins with r" and treats backslashes as ordinary characters. Add hashes when the text contains a quote, such as r#"He said "hi"."#.
Creating Strings
Create an owned string with String::from, .to_owned(), or .to_string():
fn main() {
let literal: &str = "hello";
let mut owned = String::from(literal);
owned.push('!');
owned.push_str(" world");
println!("{owned}");
}Growing and changing a `String`
push appends one char; push_str appends a string slice. Both require a mutable String. They preserve UTF-8 validity while growing the allocation as needed.
Exercise
Which type should a read-only function usually accept, String or &str?
Show answer
&str, because it can read both string literals and borrowed views of owned String values.