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(¬e);
print_menu(¬e2);
}
The output:
Menu: Iced Tea
Menu: Egg Pancake
Menu: Sweet Pancake
- Text written straight in the code, such as
"Iced Tea", is called a text literal, and its type is&str. The text is stored inside the program itself, and you only borrow it. String::from("...")and"...".to_string()make aString: a copy of your own that can be added to.¬eborrows aString's text as a&str. That is why a function that only reads text should take a&str: it can be called with a text literal or a&String(a borrow of aString).- If the parameter
nameis aString, calling the function with"Iced Tea"is refused:expected `String`, found `&str`, with the suggestion"Iced Tea".to_string().
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!
.push_str(text)adds text at the end, and.push(character)adds onechar(single quotes). Both changenote, so it must belet mut.format!works likeprintln!, but its result is kept as a newStringinstead of printed.noteis only borrowed, so it can still be used afterwards.
+ 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 |
êuses bytes 2 and 3.&menu[0..4]stops right afterê, so the result isCrê.&menu[0..3]cutsêin half. The cut would hold half a letter, so Rust chooses to panic while the program runs: the message says byte 3 is not the edge of a character (not a char boundary).- That is also why
menu[0](reading one letter by its number) isn't allowed in Rust: the code is refused withthe type `str` cannot be indexed by `{integer}`. For letters, use.chars(), which reads the text letter by letter:menu.chars().count()gives 5, andmenu.chars().nth(2)(letter number 2, counting from 0) givesSome('ê').
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
.trim()removes the spaces at the start and end. Its result is a&strthat borrowsline..split(' ')cuts the text at every space. Its result isn't a finished list but pieces taken one at a time, so.collect()gathers them into aVec<&str>. If you only need how many there are, use.count():"hello, rust".split(", ").count()gives 2..replace("x", "")makes a new String without the letterx, then.parse()turns"2"into a number.parts[1..].join(" ")joins word number 1 to the last word with spaces.parts[1..]is a slice with no end given: from number 1 to the last item..to_lowercase()and.to_uppercase()make a new String in small or capital letters, while.contains("sweet")givestrueorfalse. The original text doesn't change.
⚠️ Text that moves, gets cut, or gets miscounted
- Using a String after
+.+moves the String on its left. Useformat!when every part is still needed. - Taking
len()for the number of letters.len()counts UTF-8 bytes. Number of letters:.chars().count(). - Cutting inside a letter.
&menu[0..3]on"Crêpe"panics:is not a char boundary. text[0]. A String can't be read with a single number. Use.chars().nth(0).- A
Stringparameter for a function that only reads. Use&str, so it can be called with a text literal or a&String.
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), ¬e (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(¬e);
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 ¬e (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).