A string holds text. In Rust, its two main forms are `&str` and `String`. Both use UTF-8, so text can include letters from many languages and emoji. section 2.2
A `&str` is a string slice: a view of text, with a pointer to where the data starts and a length. A string literal such as `"Hello!"` gives you a `&str`. A `String` owns its data and can grow, shrink, or change. Use `String::from("Hello!")` when you want an owned string. section 2.2
Bytes are not always characters
`"Hello!".len()` is 6, and `"안녕!".len()` is 7—even though the second string has only three characters. That is because `.len()` counts bytes. Use `.chars().count()` to count the characters in these examples. section 1.3
fn main() {
let str1 = "Hello!";
println!("str1 is {} bytes and also {} characters.", str1.len(), str1.chars().count());
let str2 = "안녕!";
println!("str2 is {} bytes but only {} characters.", str2.len(), str2.chars().count());
}
Run the example to compare `.len()` with `.chars().count()` on both strings. section 1.3
The `&` matters: a bare `str` can have different lengths, so it cannot be used as an ordinary local variable whose size must be known. If you declare `let my_name: str = "My name";`, the compiler suggests `&str` instead. The message is a useful clue, not a sign that strings are off-limits. section 2.2
For an owned `String`, `.push()` adds a character and `.push_str()` adds a string slice. If repeated additions cause many reallocations, `String::with_capacity()` can reserve space in advance. Other available methods include `.pop()` to remove the last character and `.retain()` to keep only characters that meet a condition. section 20.8
fn main() {
let mut my_string = String::from("Age: 20 Height: 194 Weight: 80");
my_string.retain(|ch| ch.is_alphabetic() || ch == ' ');
dbg!(my_string);
}
This example uses `.retain()` to keep letters and spaces while removing digits and punctuation. section 20.8























