String vs &str
Ownership of text.
Owned vs Borrowed Text
Rust separates text ownership into two types:
String— owns its data on the heap.&str— borrows a view of text it does not own.
fn main() {
let owned = String::from("I own this");
let borrowed: &str = "I am borrowed";
println!("{} / {}", owned, borrowed);
}Where the Data Lives
A String stores its bytes on the heap and can grow. A string literal &str is baked into the program binary and is fixed.
fn main() {
let mut heap = String::from("grows");
heap.push_str(" bigger");
let fixed = "never changes";
println!("{} | {}", heap, fixed);
}All lessons in this course
- String vs &str
- Slices
- String Methods
- UTF-8 and Chars