Rust strings are more than just sequences of characters. They include metadata like length and capacity, which helps manage memory and operations efficiently. This makes them a data structure, not just plain text.
let s = String::from("hello"); println!("Length: {}, Capacity: {}", s.len(), s.capacity());
The string "hello" has 5 bytes, so length is 5. Capacity is also 5, as String::from reserves exactly the space needed without extra allocation.
Rust strings are UTF-8 encoded, so slicing must be done on valid character boundaries. The range 0..4 cuts inside a multi-byte character, causing a panic.
String in Rust is growable and manages capacity, making it efficient for appending characters. &str is immutable and fixed-size, char is a single character, and Vec
let mut s = String::with_capacity(5); s.push_str("hi"); println!("Length: {}, Capacity: {}", s.len(), s.capacity()); s.push_str(" there"); println!("Length: {}, Capacity: {}", s.len(), s.capacity());
Initially, capacity is 5. After pushing "hi", length is 2, capacity 5. After pushing " there" (6 more chars), length becomes 8, exceeding capacity, so capacity grows, typically doubling to 10.
