Sub topic 2
Joining Text and Handling UTF-8 Strings
Assume basic Rust syntax, ownership and borrowing, and familiarity with Option and Result.
Joining text with `+`, `format!`, and `join`
The + operator takes ownership of its left-hand String. It borrows the right-hand string as &str.
fn main() {
let first = String::from("tic");
let second = String::from("tac");
let joined = first + "-" + &second;
let result = format!("{joined}-toe");
println!("{result}");
}After first + ..., first cannot be used because it was moved. format! creates a new String without moving its arguments.
For several string slices, use join:
fn main() {
let parts = ["red", "green", "blue"];
let result = parts.join(", ");
println!("{result}");
}Slicing strings and why `s[0]` does not compile
Rust String values contain UTF-8 bytes. An integer index could point into the middle of a character, so s[0] is not allowed.
String ranges use byte offsets, but every boundary must fall between complete UTF-8 characters.
fn main() {
let s = "héllo";
println!("{}", &s[0..1]);
println!("{}", &s[1..3]);
println!("{:?}", s.get(0..2));
}The first slice is h, and the second is é. get(0..2) returns None because byte offset 2 is inside é. The indexing form would panic instead.
Iterating over bytes, chars, and graphemes
Use bytes() for raw UTF-8 bytes and chars() for Unicode scalar values. A user-perceived character, called a grapheme cluster, can contain multiple scalar values. Rust's standard library does not provide grapheme iteration; use a crate such as unicode-segmentation when that distinction matters.
Accepting `&str` in functions
Use &str for read-only text parameters. Rust can convert &String to &str through deref coercion.
fn shout(text: &str) -> String {
text.to_uppercase()
}
fn main() {
let owned = String::from("hello");
println!("{}", shout(&owned));
println!("{}", shout("world"));
}Exercise
Which parameter type lets shout accept both a string literal and a borrowed String?
Show answer
&str, because literals have that type and &String can be coerced to it.