Strings in Rust

String is text you own that can be added to (String::from, .to_string(), push_str, push). &str is a borrow for reading: a text literal (written straight in…

There is one error you will almost surely meet in your first week of Rust: expected `String`, found `&str` . Both look like plain text, but Rust really does have two main text types. String is text you own, which can be added to and changed. &str (read string slice, a piece of text) is a borrow for reading text that is stored somewhere else.

The difference is easy to see with the cashier at Rusdi's Pancake Stall. The order note he writes is his: he can add "1x iced tea" under it, and once he hands it to the kitchen he no longer holds it. The writing on the menu board is different: it can only be pointed at and read, "this one, Sweet Pancake". Pointing takes nothing away and can't add any writing. In code, the note is a String: you own it, you can add to it, and it can be moved somewhere else. The writing on the board is a &str: it is only borrowed for reading.

String and &str

This program makes one &str and two Strings. Then it sends all three to the function print_menu, which takes a &str:

fn print_menu(name: &str) {
    println!("Menu: {}", name);
}

fn main() {
    let tea: &str = "Iced Tea";
    let note: String = String::from("Egg Pancake");
    let note2 = "Sweet Pancake".to_string();
    print_menu(tea);
    print_menu(&note);
    print_menu(&note2);
}

The output:

Menu: Iced Tea
Menu: Egg Pancake
Menu: Sweet Pancake

Adding and joining text

This program adds text to the note, then makes the text of a receipt from it:

fn main() {
    let mut note = String::from("2x sweet pancake");
    note.push_str(", 1x egg pancake");
    note.push('!');
    println!("{}", note);
    let total = 102;
    let receipt = format!("{} = ${}", note, total);
    println!("{}", receipt);
    println!("{}", note);
}

The output:

2x sweet pancake, 1x egg pancake!
2x sweet pancake, 1x egg pancake! = $102
2x sweet pancake, 1x egg pancake!

+ joins text too, but in a different way. Here the cashier joins the note with +, then prints the old note again:

fn main() {
    let note = String::from("2x sweet pancake");
    let full = note + ", 1x iced tea";
    println!("{}", full);
    println!("{}", note);
}

Does it compile? Guess first, then look at the compiler's answer:

error[E0382]: borrow of moved value: `note`
 --> src/main.rs:5:20
  |
2 |     let note = String::from("2x sweet pancake");
  |         ---- move occurs because `note` has type `String`, which does not implement the `Copy` trait
3 |     let full = note + ", 1x iced tea";
  |                ---------------------- `note` moved due to usage in operator
4 |     println!("{}", full);
5 |     println!("{}", note);
  |                    ^^^^ value borrowed here after move
  |
note: calling this operator moves the left-hand side

+ takes the String on its left, adds the text on its right to its end, then hands the result to full. After that note has moved and can't be used again. So the code doesn't compile. The right side of + must be a &str, so a String on the right is written with &: note + &extra. If every part is still needed, use format!.

len() counts bytes, not letters

Rust text is stored as UTF-8: a plain letter is 1 byte, a letter such as ê is 2 bytes. You saw "Crêpe".len() give 6 in the data types lesson. Cutting text with &menu[start..end] also uses byte numbers: the result is a slice from byte start up to before byte end. This program tries three cuts:

fn main() {
    let menu = String::from("Crêpe");
    println!("len: {}", menu.len());
    println!("chars: {}", menu.chars().count());
    println!("{}", &menu[0..2]);
    println!("{}", &menu[0..4]);
    println!("{}", &menu[0..3]);
}
len: 6
chars: 5
Cr
Crê

thread 'main' (23389148) panicked at src/main.rs:7:25:
end byte index 3 is not a char boundary; it is inside 'ê' (bytes 2..4 of string)
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

This table shows which byte holds which letter:

Byte 0 1 2 3 4 5
Holds C r ê ê p e

When the cut points are not certain, for example when they come from user input, there is a way that does not panic:

fn main() {
    let menu = String::from("Crêpe");
    println!("{:?}", menu.get(0..3));
    println!("{:?}", menu.get(0..4));
    let three: String = menu.chars().take(3).collect();
    println!("{}", three);
}
None
Some("Crê")
Crê

menu.get(0..3) gives None because byte 3 is inside ê. .take(3) takes the first 3 letters from .chars(), then .collect() gathers them into a String. When to pick which way:

Way When to pick it
&menu[start..end] You are sure the cut points sit between letters, for example the result of find (a method that finds where a piece of text is).
menu.get(start..end) The cut points are not certain. The result is None when one lands inside a letter, not a panic.
menu.chars().take(n) You want the first n letters, not n bytes.

Processing an order line

A customer types " 2x Sweet Pancake ", with extra spaces. The cashier needs the number of portions and the menu name:

fn main() {
    let line = "  2x Sweet Pancake  ";
    let tidy = line.trim();
    println!("[{}]", tidy);
    let parts: Vec<&str> = tidy.split(' ').collect();
    println!("{:?}", parts);
    let portions: u32 = parts[0].replace("x", "").parse().unwrap();
    let menu = parts[1..].join(" ").to_lowercase();
    println!("{} portions {}", portions, menu);
    println!("{}", menu.contains("sweet"));
    println!("{}", menu.to_uppercase());
    println!("{}", portions * 32);
}
[2x Sweet Pancake]
["2x", "Sweet", "Pancake"]
2 portions sweet pancake
true
SWEET PANCAKE
64

⚠️ Text that moves, gets cut, or gets miscounted

TL;DR: String is text you own that can be added to (String::from, .to_string(), push_str, push). &str is a borrow for reading: a text literal (written straight in the code), &note (a borrow of the String note), or the result of trim (removes spaces at the edges of text). A function that only reads takes &str. format! makes a new String without moving anything, while + moves the String on its left (borrow of moved value). len() counts UTF-8 bytes ("Crêpe" 6), chars().count() counts letters (5), and cutting text inside a letter panics (the program stops). trim, split (cuts text into pieces, which collect gathers or count counts), replace (swaps text), contains (checks for text), to_uppercase and to_lowercase process text without changing the original.

⚡ Owned or borrowed

Write:

let tea: &str = "Iced Tea";
let note: String = String::from("Egg Pancake");
print_menu(tea);
print_menu(&note);

Meaning: String is text you own, which can be added to and changed. &str is a borrow for reading, such as the text literal "Iced Tea" (written straight in the code) or &note (a borrow of the String note). print_menu is a function that only reads text, so it should take a &str: then both forms can be sent to it.

⚡ format! or +

Guess first: let full = note + ", 1x iced tea";, then note is printed again. Does it compile?

No. + takes the String on its left, so note has moved into full. The compiler refuses with borrow of moved value: a value is used after it was moved.

Meaning: When you still need every piece of text after the join, join them with format!. format! works like println!, but it only borrows the parts and keeps the result as a new String.

⚡ len() counts bytes

Write:

let menu = String::from("Crêpe");
println!("len: {}", menu.len()); // 6
println!("chars: {}", menu.chars().count()); // 5

Meaning: Text is stored as UTF-8 bytes, and ê takes 2 bytes, so len() gives 6. The number of letters is counted with .chars().count(). Cutting text inside a letter, such as &menu[0..3] (byte 0 up to before 3), makes the program panic (stop).

What you will learn