Keyboard shortcuts

Press ← or β†’ to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Lecture 23 - Strings: why they're so complicated

A row of cells where one character spans two of them

Announcements




Friday's loose end

Earlier, we saw names[0] couldn't take a String out of a vector.

Today we see a similar problem:

fn main() {
    let text = String::from("hello");
    let c = text[0];
    println!("{}", c);
}

You can't take a character out of a String either!

A Vec<char> would let you. A String won't. Why?

And one more:

fn main() {
    println!("{}", "πŸ¦€".len());
}

What will this print?

By the end of today both of these will make (some) sense.

Learning Objectives

By the end of today, you should be able to:

  • Tell String, &str, and &String apart, and draw each one
  • Say what a slice is and why it has no capacity
  • Explain why text[0] doesn't compile, and what .len() counts
  • Use .chars(), .iter(), and .collect() to take text apart and put it back

A slice is a view

A slice is a reference to a contiguous run of elements inside something else.

Think of it as a window through which you can see some of the elements.

fn main() {
    let data = [1, 2, 3, 4, 5, 6];
    let slice1 = &data[1..4];    // [2, 3, 4]
    let slice2 = &data[..3];     // [1, 2, 3], from the start
    let slice3 = &data[2..];     // [3, 4, 5, 6], to the end
    println!("{:?} {:?} {:?}", slice1, slice2, slice3);
}

The type is &[T]: a slice of Ts, a view onto someone else's array (or array-like thing). start..end includes start and stops before end, the same as a for range.

You've sliced before

Syntax like Python, behavior like numpy.

arr = np.array([1, 2, 3, 4, 5, 6])
view = arr[1:4]         # a VIEW into arr's buffer, no copy
view[0] = 99            # arr is now [1, 99, 3, 4, 5, 6]

df.iloc[1:4]            # pandas: same syntax, view or copy?

A numpy slice is a window onto the original array, which is exactly what &data[1..4] is.

Pandas is the cautionary tale: whether .iloc[1:4] gave you a view or a copy depends on the version and the dtypes! (You've probably seen those SettingWithCopyWarnings lots of times.)

Rust is clear and consistent: &[T] is always a view.

A slice in memory

let v = vec![10, 20, 30, 40, 50];
let x = &v[1..4];     // the 20, 30, 40
Stack:                        Heap:
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ main()          β”‚           β”Œβ”€β”€β”€β”€β”¬β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”
β”‚ β”œ v: Vec<i32>   β”‚           β”‚ 10 β”‚ 20 β”‚ 30 β”‚ 40 β”‚ 50 β”‚
β”‚ β”‚  β”œ ptr ───────┼──────────▢│    β”‚    β”‚    β”‚    β”‚    β”‚
β”‚ β”‚  β”œ len: 5     β”‚           β””β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”˜
β”‚ β”‚  β”” cap: 5     β”‚                  β–²
β”‚ β”” x: &[i32]     β”‚                  β”‚
β”‚    β”œ ptr β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  (at the 20)
β”‚    β”” len: 3     β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

A slice has two parts: a pointer and a length. It points into the heap, not at the handle. There's no cap, because the slice can't grow.

That makes it a "fat pointer" that points to a range in memory.

Activity 23, Problem 1: draw the slice

See Problem 1 on Activity 23.

Three and two. data is pointer, length, capacity. slice is pointer and length only. No capacity, because a slice doesn't own what's on the heap and can't grow it.

Slices of anything contiguous

fn main() {
    let a = [1, 2, 3, 4, 5];
    let a_slice: &[i32] = &a[1..4];
    println!("{:?}", a_slice);

    let v = vec![1.1, 2.2, 3.3, 4.4, 5.5];
    let v_slice: &[f64] = &v[2..];
    println!("{:?}", v_slice);

    let s = String::from("Hello World");
    let s_slice: &str = &s[0..5];
    println!("{}", s_slice);

    let smaller: &[f64] = &v_slice[0..2];   // a slice of a slice
    println!("{:?}", smaller);
}
  • &[T] is a slice of an array or a Vec
  • &str is a slice of text. Same two things, pointer and length.

Mutable slices

fn main() {
    let mut numbers = [10, 20, 30, 40, 50];
    {
        let slice = &mut numbers[1..4];
        slice[0] = 999;              // index 0 of the slice is index 1 of the array
    }                                // the slice ends here
    println!("{:?}", numbers);       // [10, 999, 30, 40, 50]
}

Indexes are relative to the slice, not to the array underneath.

Heads down: two slices, no overlap

What happens?

let mut data = vec![1, 2, 3, 4];
let slice1 = &data[0..2];
let slice2 = &mut data[2..4];
println!("{:?} {:?}", slice1, slice2);

A) Compiles fine. The slices don't overlap: indexes 0 and 1 versus 2 and 3
B) Compiler error: Rust stops you from doing something risky
C) Runtime panic

B. The two slices really don't overlap, and the compiler rejects it anyway.

There's a rule about mixing & and &mut that explains this, and we'll get to it soon.

The handle, or the text?

Two ways to point at a String:

fn main() {
    let s = String::from("Hello");
    let whole: &String = &s;
    let text: &str = &s[..];      // all of s's text, as a &str

    println!("address of s     {:p}", &s);
    println!("s's ptr          {:p}", s.as_ptr());
    println!("whole points to  {:p}", whole);
    println!("text points to   {:p}", text);
}

whole matches the address of s. It points at the handle, on the stack.

text matches s's ptr. It points at the letters, on the heap, and carries a length.

Three types of string

let s = String::from("Hello");      // owned: a handle on the stack, letters on the heap
let s_ref: &String = &s;            // a reference to the handle
let slice: &str = &s[..];           // a slice of the letters: pointer + length
let literal: &str = "literal";      // also a slice, but of text baked into the program
Stack:                       Heap:
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ main()            β”‚        β”Œβ”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”
β”‚ β”œ s: String       │◀──┐    β”‚ 'H' β”‚ 'e' β”‚ 'l' β”‚ 'l' β”‚ 'o' β”‚
β”‚ β”‚  β”œ ptr ─────────┼───┼───▢│     β”‚     β”‚     β”‚     β”‚     β”‚
β”‚ β”‚  β”œ len: 5       β”‚   β”‚    β””β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”˜
β”‚ β”‚  β”” cap: 5       β”‚   β”‚       β–²
β”‚ β”œ s_ref: &String β”€β”Όβ”€β”€β”€β”˜       β”‚
β”‚ β”œ slice: &str     β”‚           β”‚
β”‚ β”‚  β”œ ptr β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
β”‚ β”‚  β”” len: 5       β”‚        Program binary (read-only):
β”‚ β”” literal: &str   β”‚        β”Œβ”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”
β”‚    β”œ ptr ─────────┼───────▢│ 'l' β”‚ 'i' β”‚ 't' β”‚ 'e' β”‚ 'r' β”‚ 'a' β”‚ 'l' β”‚
β”‚    β”” len: 7       β”‚        β””β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”˜
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
  • String owns its letters. Three fields: ptr, len, cap
  • &String is one arrow, to the handle
  • &str is a slice: ptr and len, no cap. The letters can be on the heap, or in the program itself. A literal like "literal" is compiled into the binary and lives for the whole run

&str parameters take both

fn analyze_text(text: &str) -> usize {
    text.len()
}

fn main() {
    let s = String::from("Hello");
    let s_ref: &String = &s;

    println!("{}", analyze_text(s_ref));      // &String, converted for you
    println!("{}", analyze_text(&s));         // same thing
    println!("{}", analyze_text("literal"));  // &str directly
}

When you hand a &String to a function that wants a &str, Rust converts it for you.

So we generally use &str in signatures. A function taking &str accepts a &String, a literal, or a piece of either. A function taking &String accepts only &String.

&str in, String out is the usual shape for a function that builds new text.

Activity 23, Problem 2: two frames

See Problem 2 on Activity 23.

Three ways to join text

fn main() {
    // 1. format!: works with anything, and you keep all of it
    let name = "Data";
    let num = 210;
    let result = format!("{} Science {}", name, num);

    // 2. push_str: add onto the end of a String you already have
    let mut s = String::from("Hello");
    s.push_str(" World");

    // 3. +: the left side must be a String, and it gets used up
    let s1 = String::from("Hello");
    let s2 = s1 + " World";          // s1 is gone after this line

    println!("{} | {} | {}", result, s, s2);
}

format! is a safe default.

Why the crab is 4 bytes long

Unicode gives every character in every writing system a number, its code point:

CharacterCode point
AU+0041
Γ©U+00E9
δ½ U+4F60
πŸ¦€U+1F980

A Rust char holds that number directly, so a char is always 4 bytes.

UTF-8 is the way those numbers are written into memory and files. It's variable-length: the first 128 code points take one byte each, so plain ASCII text is unchanged, and everything else takes two, three, or four.

Character   UTF-8 bytes    Bits
'A'         1              01000001
'Γ©'         2              11000011 10101001
'δ½ '        3              11100100 10111101 10100000
'πŸ¦€'        4              11110000 10011111 10100110 10000000

A Rust String is UTF-8. Its len counts those bytes.

len is bytes, chars is characters

fn main() {
    let emoji = "πŸ¦€πŸš€";
    println!("bytes {}, chars {}", emoji.len(), emoji.chars().count());

    let accents = "AΓ©";
    println!("bytes {}, chars {}", accents.len(), accents.chars().count());
}

.len() counts bytes, .chars().count() counts characters. When a string test is off by one or two, this is usually why.

So that's why text[0] is rejected

If text[0] compiled, it would have to return one byte. For "πŸ¦€" that is the first quarter of a crab, which isn't a character at all. Rust refuses at compile time rather than hand you garbage.

The safe way to look at the pieces is .chars(), which is Part 3. First, a question.

Heads down: what happens?

fn main() {
    let emoji = "πŸ¦€";
    let slice = &emoji[0..2];
    println!("{}", slice);
}

A) Prints πŸ¦€
B) Prints nothing
C) Compiler error
D) Runtime panic

D. Slicing is by bytes and the boundary check happens at run time. Byte 2 is inside the crab, so the program panics.

Slicing by byte range compiles

text[0] is refused at compile time. &text[0..2] isn't: the range is checked at run time, and the check is "does each end land on a character boundary?"

fn main() {
    let text = "Hello, world!";
    println!("{}", &text[0..5]);     // "Hello": every ASCII character is one byte

    let text = "πŸ¦€Hello";
    println!("{}", &text[4..9]);     // "Hello": starts right after the 4-byte crab
    println!("{}", &text[0..4]);     // "πŸ¦€": the whole crab is fine
}

On plain ASCII, byte positions and character positions agree, so this works and tests pass. The first accented name or emoji in the data is where they break down.

chars, iter, and collect

You can't get far with text without these. .chars() and .iter() let you break variable-sized characters up, and .collect() is how you put them back together.

.iter() and .collect() are much more powerful than just this, but we'll wait til the end of the term to explore them more. For now, they do stuff like this:

fn main() {
    // iterate characters, not bytes
    for ch in "Hi!".chars() {
        println!("{}", ch);                              // ch is a char
    }

    // char to String
    let c: char = 'πŸ¦€';
    let s: String = c.to_string();

    // iter() over a Vec gives you sum, max, and friends
    let numbers = vec![1, 2, 3, 4, 5];
    let total: i32 = numbers.iter().sum();
    let largest = numbers.iter().max();                  // Some(5); None if empty
    println!("s: {} total: {} largest: {:?}", s, total, largest);
}

collect builds whatever type you ask for

The type annotation on the left is the instruction.

fn main() {
    let letters = vec!['H', 'e', 'l', 'l', 'o'];
    let word: String = letters.iter().collect();          // chars into a String
    println!("{}", word);

    let text = "Hello";
    let chars: Vec<char> = text.chars().collect();        // a String into chars
    println!("{:?}", chars);

    let first_three: String = "Hello World".chars().take(3).collect();   // and back
    println!("{}", first_three);
}

Vec<char> is the one type where [0] works on text, because every element is exactly one char. It costs 4 bytes a character.

Heads down: which would you write?

Two ways to keep the first three characters:

// A: takes &mut, changes the caller's String in place
fn keep_first_three(s: &mut String) {
    *s = s.chars().take(3).collect();
}

// B: takes &str, returns a new String
fn first_three(s: &str) -> String {
    s.chars().take(3).collect()
}

A) A
B) B
C) Depends on context

C, with B as the default. A changes the caller's text and needs &mut. B leaves the original alone and creates a new String. A is only right if the caller wants to completely replace the original.