1. Borrowing Briefly Instead of Moving Ownership (&T)
print_length(item) in Part 4 only needed to measure the name, but the call moved it out of main. This time we'll count a letter and print the original name next to the count.
In cases like this, you can put an ampersand (&) in front of the value to pass a reference instead. Keeping ownership with the original variable while temporarily lending access is called borrowing.1
Think of it like lending a book to a friend so they can read it and hand it back, rather than giving it away for good. In memory, Rust does not copy the long string on the heap.
It only passes a lightweight address (pointer) showing where that data lives, and when the function finishes, the reference goes away while the original string stays safely with its owner.
fn count_letter(item: &str, target: char) -> usize {
let mut count = 0;
for ch in item.chars() {
if ch == target {
count += 1;
}
}
count
}
fn main() {
let item = String::from("iced tea");
let count = count_letter(&item, 't');
println!("Occurrences of t in {}: {}", item, count);
}Output:
Occurrences of t in iced tea: 1count_letter takes the borrowed item name (item: &str) and the character to find (target: char). It returns the count as an unsigned size, usize.2
Each trip through item.chars() reads one character and compares it with target. We pass 't' from main, so the counter goes up once, at the t in iced tea.
The final line count has no semicolon (;) because it is the return value of the function.
count_letter(&item, 't') borrows the name. main still owns it, so the next line can print the name and the count together.
Here is one detail that often trips up beginners at first. A reference created with just & is read-only (an immutable reference) by default.
If you try to append to or modify the borrowed string inside the function, the compiler immediately raises an error to prevent silent changes to the original value.
2. Modifying Borrowed Values (&mut T) and Borrow Checker Rules
So what if you do want a function to append new text to the original string? In that case, you pass a mutable reference (&mut String) by adding mut after &.
It explicitly grants permission to both read and modify the value.
If anyone could modify the original data freely, things would quickly get tangled. That is why the Rust compiler includes a strict gatekeeper called the borrow checker.
The principle it enforces works just like the rules of a shared document or a library reading room.
Picture opening a shared document in read-only mode (&T). Nobody is changing the text, so ten people can read it at the same time without seeing inconsistent content.
On the other hand, while someone holds an edit lock (&mut T) to rewrite a sentence, no one else can read or edit it at the same time.
To sum it up, at any given point you can have either multiple immutable references (&T) to the same value, or exactly one mutable reference (&mut T). Mixing both at the same time is never allowed.
This rule may look strict, yet it prevents two serious classes of bugs before your program ever runs.
The first is a data race: when two places access the same memory at once and one of them overwrites it, the reader can end up seeing half-updated, corrupted data.
The second is iterator invalidation. If one part of your code is walking through a string or list while another part appends a lot of data, the heap buffer may move to a larger block of memory.
Without the borrow checker, the reader would keep pointing at the old, freed address and crash or read garbage, so Rust stops this bug at compile time.
fn append_item(items: &mut String, item: &str) {
items.push_str(", ");
items.push_str(item);
}
fn main() {
let mut items = String::from("tea");
append_item(&mut items, "toast");
append_item(&mut items, "jam");
println!("Order: {}", items);
}Output:
Order: tea, toast, jamappend_item(items: &mut String, item: &str) takes the order string to edit and the name to append. Two calls to push_str add a comma and space, then the name.
Because it modifies the original value in place, it does not need to return anything.
Declare let mut items in main so you can pass &mut items to the function. The original variable has to allow mutation for you to borrow it that way.
The first call appends "toast" and ends. The next one appends "jam" to the same string, with a fresh mutable borrow.
By contrast, if you create let a = &mut items; and let b = &mut items; at the same time and try to use both, the compiler stops you right away. Holding onto a read-only reference (&items), calling a mutable borrow (&mut items), and then using the old read-only reference again is rejected too.
Whenever the rule feels tricky, just ask yourself: are two hands holding an edit lock at once, or is someone editing while another is reading?
3. What Is the Difference Between String and &str (String Slice)?
One of the most common questions from Rust beginners is: "Why are there two string types, String and &str?" The dividing line between them is ownership.
String is an owned string with its own buffer allocated on the heap. Think of it as a notebook you bought yourself.
You can append text to make it grow, and when it leaves scope, its owner cleans up the memory.
By contrast, &str (a string slice) is a transparent window into all or part of a UTF-8 string that already lives somewhere else. Instead of copying characters, it only carries a starting address and a length.
Even a string literal like "tea" written directly in your code has type &str, borrowing text stored inside the compiled executable.
fn main() {
let owned: String = String::from("tea, toast");
let whole: &str = &owned; // borrow the whole string
let first_three: &str = &owned[0..3]; // slice the first 3 bytes
println!("Whole: {}, Prefix: {}", whole, first_three);
}Output:
Whole: tea, toast, Prefix: teaOn the first line, owned is a String that allocates and owns "tea, toast" on the heap. On the second line, &owned starts as &String, and Rust automatically converts it into a &str window viewing the entire string and stores it in whole.
The range 0..3 in &owned[0..3] starts at byte 0 and stops just before byte 3. It borrows those bytes without copying them. Here t, e, and a take one byte each, so the slice happens to contain exactly the three letters in tea.
UTF-8 uses different byte counts for different characters: κ° takes three bytes, and π± takes four. The byte range [0..3] in "κ°λλ€" selects "κ°". Slicing with [0..2] stops in the middle of that first character, so Rust panics instead of producing invalid text.
Use get(0..2) when you need to check the range without panicking: it returns None at that invalid boundary. To read Unicode scalar values one at a time instead of counting bytes, use .chars().
Finally, keep one practical rule of thumb in mind. When a function parameter only needs to read a string, prefer &str over &String.
A parameter of type &String only accepts references to String variables, whereas &str accepts a String reference (&owned), a partial slice (&owned[0..3]), and a string literal ("tea") all with the same function.
That's why count_letter in Section 1 accepts &item and would also accept "tea" directly. The function only borrows the text it reads.
In Part 6 we'll bundle a quantity and its unit price into a struct, then use an enum for commands that update an order.
Footnotes
- The Rust Programming Language, Ch. 4.2 References and Borrowing. https://doc.rust-lang.org/book/ch04-02-references-and-borrowing.html β©
- The Rust Programming Language, Ch. 4.3 The Slice Type: https://doc.rust-lang.org/book/ch04-03-slices.html β©