Rust has two main string types, and understanding them is crucial!
| Type | Ownership | Mutability | Location |
|---|---|---|---|
String | Owned | Can be mutable | Heap |
&str | Borrowed | Immutable | Anywhere |
let s1: &str = "hello"; // String literal (in binary)
let s2: String = String::from("hello"); // Owned, heap-allocated
let s3: &str = &s2; // Borrow String as &strlet mut s = String::from("hello");
s.push(' '); // Append char
s.push_str("world"); // Append &str
s += "!"; // Concat with +=
let combined = format!("{} {}", "hello", "world");// &str → String
let owned = "hello".to_string();
let owned = String::from("hello");
// String → &str
let borrowed: &str = &owned;Strings in Rust are UTF-8 encoded. Indexing by byte position can be dangerous!
let s = "hello world";
s.len() // Byte length
s.is_empty() // Check if empty
s.contains("world") // Substring check
s.split_whitespace() // Iterator over words
s.chars() // Iterator over charsImplement reverse_words(s) that reverses the order of words.
"rust is awesome""awesome is rust"fn reverse_words(s: &str) -> String {
s.split_whitespace()
.rev()
.collect::<Vec<_>>()
.join(" ")
}Or:
let words: Vec<&str> = s.split(' ').collect();
words.into_iter().rev().collect::<Vec<_>>().join(" ")