Rust String and UTF-8
Choose owned text or a borrowed view and count the intended unit.
How it works
String owns growable UTF-8 text; &str is a borrowed UTF-8 view. len counts bytes, while chars iterates Unicode scalar values. Neither automatically counts grapheme clusters such as a composed user-perceived symbol. Rust does not permit simple integer indexing into a String because byte and character boundaries are different. Use text operations that match the application’s actual meaning.
Run the code
Reviewed with Rust 1.97.0, edition 2024, using the standard library only. Save the complete download as lesson-name.rs in a separate learning folder, compile with rustc --edition=2024 lesson-name.rs and run the resulting program (lesson-name.exe on Windows). Use the actual lesson filename. The final project includes complete Cargo package files; run cargo test --offline and cargo run --offline from that separate package folder. There is no Rust browser runner; PHP, Apache and MySQL are not needed.
This complete example was executed in the stated local review environment.
Example
fn main() {
let mut label = String::from("café");
assert_eq!(label.len(), 5);
assert_eq!(label.chars().count(), 4);
label.push_str(" tray");
assert_eq!(label, "café tray");
println!("UTF-8 label: café tray");
}
Expected result
UTF-8 label: café tray
The accented character occupies more than one UTF-8 byte, making the two counts intentionally different. push_str appends another valid string slice to the owned allocation. A user interface with complex writing systems may need a maintained Unicode segmentation library rather than assuming chars equals visible characters.
Primary technical reference: Rust documentation.