Skip to lesson content
navan✳THE BUILD LABRUST
0/53 complete
BUILD LAB / RUST/ COLLECTIONS THAT WORK
BUILD NOTE 20 / 53

Text has more than one length.

Own, borrow, build, and iterate through UTF-8 text.

BY NAVAN SAMI◷ 7 MIN READFOUNDATIONSRUST 2024

01 Understand the contract

String owns a growable UTF-8 buffer; str is the dynamically sized text type usually used through &str. Use push for a char, push_str for a string slice, and format! when building a new formatted String. len counts bytes, chars iterates Unicode scalar values, and split_whitespace separates runs of whitespace. Case conversion can change the byte length. Be explicit about the text operation your product needs, especially for names, search, and cursor movement.

02 Make it concrete

This is a complete standard-library example. Use Rust stable with the 2024 edition. Run it locally using the Rust workbench.

lessons/strings/src/main.rs
fn main() {
    let mut title = String::from("Rust");
    title.push_str(" café");
    println!("{title}");
    println!("bytes={}, scalars={}", title.len(), title.chars().count());
    println!(
        "{}",
        title.split_whitespace().collect::<Vec<_>>().join(" / ")
    );
}
↳ EXPECTED OUTPUT
Rust café
bytes=10, scalars=9
Rust / café
  1. 1

    The é needs two bytes in UTF-8.

  2. 2

    split_whitespace returns borrowed words.

  3. 3

    join constructs a new owned String.

From the extracted rust-workbench folder
cargo run -p lesson_strings

03 Mind the boundary

04 Your next build

A SMALL MISSION

Reverse the Unicode scalar sequence of a string and test an accented word.

Reveal one possible solution +
solutions/strings/src/main.rs
fn reverse(s: &str) -> String {
    s.chars().rev().collect()
}
fn main() {
    assert_eq!(reverse("café"), "éfac");
    assert_eq!(reverse(""), "");
}

05 Check your reasoning

QUICK SIGNAL CHECK

Which method counts UTF-8 bytes?

ONE MORE CONTRACT YOU CAN EXPLAIN.

Understand it.
Then make it yours.

Run the example, try your own input, and explain the boundary. Log the lesson when the idea makes sense.

Built with curiosity. By Navan Sami. ↗Rust · Make the contract clear. Then build.