Rust for a C programmer · Lesson 02 · 5–10 minutes
Borrow a string for a call
Let a function read your text, then keep using the same owned string.
First, recall the move
In lesson 01, show(name: String) received show(name).
Who owned the string during that call, and could main use it afterward?
Check the earlier rule
The parameter inside show owned it. Passing the String by value
moved it out of main; returning did not give it back.
Ownership and functions.
Read without taking ownership
Borrowing means accessing data while ownership stays elsewhere.
Creating a reference borrows a value: in let r = &name;,
&name borrows name, and r holds the resulting reference.
Rust checks that the referenced data stays valid while you use it.
References and borrowing.
String, &String, and &str
&T means a shared reference to a value of type T.
Shared means you can read through this reference, but cannot use it to change this text.
Start with the owner, then distinguish two ways to borrow:
| Type | What it represents |
|---|---|
String | A standard-library type that owns a growable UTF-8 buffer, tracking its pointer, byte length, and capacity. Dropping it releases its allocation. |
&String | A shared reference to that owning String object. It does not own or free the buffer. |
&str | A shared view of UTF-8 text: a pointer to the bytes plus their byte length. It does not own or free the text. |
str is a built-in language type for a sequence of UTF-8 text bytes; &str
is a reference to that type, not shorthand for &String.
A str has no fixed size at compile time, so we normally access it through a reference
that carries its length. Such a view can cover a whole String, part of one, or text stored in the
program as a string literal. Creating the view does not copy the text.
The Rust Book: defining strings ·
String slices.
For a helper that only reads text, &str is the usual choice even for the entire string. It allows more inputs than
&String: it does not require an owning String object. Think of the purpose served
by a C const char * plus a length, with validity checked by Rust and no required
terminating zero. The function below uses that more general view.
String slices as parameters.
What if the data is arbitrary bytes?
u8 is an unsigned eight-bit integer. A fixed array of four bytes has type
[u8; 4]; a borrowed byte slice has type &[u8].
The slice carries a pointer and a length, so its type does not specify a fixed byte count.
Vec<u8> is an owned, growable byte buffer.
Unlike string types, these byte containers allow any byte sequence, including invalid UTF-8.
Compare byte and text types ·
The Rust Book: arrays ·
Other slices.
The supplied exercises/borrowing/src/main.rs
fn show(name: &str) {
println!("{name}");
}
fn main() {
let name = String::from("report.txt");
show(&name);
println!("still owned: {name}");
}
&str in the parameter type describes the view accepted.
&name at the call creates an &String, which Rust automatically converts
to &str. The function borrows text without cloning it or taking ownership.
String slices as parameters.
Predict the output, then run
Open src/main.rs and run the supplied project:
cd "/home/dmedeiros/Documents/ChatGPT/Teach Me Rust/exercises/borrowing"
cargo run
Compare output and cleanup
report.txt
still owned: report.txt
main owns the String throughout. Ending show’s reference
does not free the text. In this program, the String is dropped when main
finishes normally.
Borrowed arguments and cleanup.
At scope exit, Rust drops values still owned there. A move transfers cleanup responsibility
to the new owner; the last use alone does not trigger cleanup.
If you add another print that does not mention name after the final print above,
the String is still dropped at main’s closing brace.
The Rust Book: cleanup at scope exit.
Why wait for scope exit?
Cleanup can affect the rest of a program. A lock guard is a value that keeps a mutex locked until the guard is dropped. If the block keeps ownership of the guard, the lock remains held until that block ends, even when later statements do not mention the guard. Dropping it at its last use could release the lock before the protected work finishes. The Rust Book: lock guards and cleanup.
Moving the guard into a function transfers responsibility for releasing the lock. That function may drop it, return it, or move it elsewhere; the caller can no longer assume the lock is still held after the call. If later work requires the lock, keep the guard and lend the function a reference. Scope exit drops values still owned there; the original scope does not clean up a value it has moved away. The Rust Book: ownership and functions.
The guard and borrow checks protect access to the mutex’s data. They do not establish that your whole operation holds its locks for long enough or in the right order; safe Rust programs can still have synchronization logic errors and deadlocks. The Rust Book: shared-state concurrency and deadlocks.
For the string example, drop(name) explicitly requests earlier cleanup. It takes
ownership of the String and frees its buffer before returning; name
cannot be used afterward. An inner block also lets you choose an earlier scope exit.
The Rust Book: dropping a value early.
Example: keep the lock guard in the caller
The caller owns a MutexGuard, the value that keeps this mutex locked.
The helper borrows the protected counter. It checks availability and decrements the counter
while the same lock is held.
The Rust Book: mutexes and guards.
use std::sync::Mutex;
fn take_one(stock: &mut u32) -> bool {
if *stock == 0 {
return false;
}
*stock -= 1;
true
}
fn main() {
let stock = Mutex::new(1_u32);
{
let mut guard = stock.lock().expect("stock lock poisoned");
let taken = take_one(&mut *guard);
println!("taken: {taken}, remaining: {}", *guard);
// The caller still owns the guard after the helper returns.
} // Dropping the guard releases the lock here.
println!("lock released");
}
*guard accesses the protected u32; &mut *guard lends
a mutable reference to that counter. let mut guard permits this mutable access.
Inside the helper, *stock accesses the same counter through the reference.
The guard implements Deref and DerefMut, Rust interfaces that define
shared and mutable dereferencing.
Mutable references ·
Following a reference with *.
The helper receives &mut u32, so it cannot drop the caller’s guard or unlock
this mutex. The guard remains in the inner block after the helper returns and is dropped
at that block’s closing brace, even though the last explicit use is the preceding print.
-> bool declares the return type. The final true has no semicolon,
so it becomes the return value; an empty counter returns false early.
Functions with return values.
The example uses one thread to isolate lock duration. expect panics if locking reports
a poisoned mutex, which can happen after a thread panics while holding it.
Run the saved guard example
from the borrowing project. Cargo treats a file in examples/ as an example executable:
cd "/home/dmedeiros/Documents/ChatGPT/Teach Me Rust/exercises/borrowing"
cargo run --offline --example guard_in_caller
Expected output:
taken: true, remaining: 0
lock released
Can a function return a borrow?
A function can return a reference to data that remains valid after the call. The borrow can continue after the function returns; it is not limited to the function's execution. A returned reference does not keep an allocation alive. Rust rejects a reference into a local String that would be dropped on return. If the function creates and owns a new buffer, return its String to transfer ownership to the caller. The Rust Book: dangling references.
fn make_name() -> String {
// Return the owned String; ownership moves to the caller.
String::from(" report.txt ")
}
fn trimmed_name(name: &str) -> &str {
// The returned view borrows the caller's bytes.
name.trim()
}
fn main() {
let name = make_name();
let view = trimmed_name(&name);
println!("{view}");
} // The owned String is dropped here.
make_name allocates the text and returns its owner. Moving that String into
main's name does not copy the text or free the buffer.
trimmed_name then returns a view that excludes surrounding whitespace, using
trim(). The bytes remain owned by name.
Returning ownership.
A reference's lifetime is the region of code for which it is valid.
With this single borrowed input, Rust infers the relationship between input and output lifetimes:
the returned view can be used only while the borrowed text stays valid. This relationship does
not extend the owner's life. Returning a reference to a local owner that is dropped is rejected
at compile time, as is inserting drop(name); before the later use of view.
Dropping name after the final use of view is allowed.
Optional reading: inferred lifetime relationships.
Run the saved returned-borrow example
from the borrowing project with cargo run --offline --example returned_borrow.
It prints report.txt.
Remove one character
Change show(&name) to show(name). Predict whether this version compiles,
then save and run cargo check.
Read the diagnostic
Expect E0308, “mismatched types”: the function requires &str,
but the argument is String. This signature asks for a borrowed view, so supplying
the owned value does not satisfy it. Rust suggests borrowing with &name.
Restore the & and run cargo check again. It should succeed.
Cargo’s check/run cycle.
Try a different source of text
Add show("inline.txt"); after the existing call. Does this need an &
too? Predict, then run it.
Check the argument’s type
The literal is already &str. Its UTF-8 bytes are stored in the program's
binary; there is no owning String object behind this literal and no growable heap buffer to
allocate or free. The view still carries a pointer and a byte length. Its full type is
&'static str: 'static means the referenced text remains valid
for the entire program. String::from("inline.txt") instead creates an owned copy.
The call prints inline.txt between the original two lines.
String literals as slices.
Build two programs from scratch
Create a separate Cargo project for each exercise, then replace its generated
src/main.rs with your own program. Choose the function signatures yourself.
Use the standard library; no dependencies are needed.
cd "/home/dmedeiros/Documents/ChatGPT/Teach Me Rust"
cargo new exercises/text-report
cargo new exercises/unquote
Inside each project, use cargo check while writing and cargo run
to compare your output with the examples below.
The Rust Book: creating a Cargo project.
1. Report text without taking ownership
Write a function named report that reads text and prints the text followed by
its length in bytes. Choose a parameter type that accepts both borrowed String contents and literals.
- In
main, create an owned String containingnotes.md. - Call
reportwith that string, then call the same function with the literalREADME. - After both calls, print the original owned string again from
main. - Keep ownership in
main. The helper must not clone the input or create an owned copy.
Expected output:
notes.md: 8 bytes
README: 6 bytes
still owned: notes.md
Also check that an empty input reports zero bytes and café reports five bytes.
For the latter case, the final letter is the single character é.
Method reminder
text.len() gives the byte length. The task is to choose the input type and
call syntax that let one function read either source of text without taking ownership.
The Rust Book: string slices as parameters.
For review: explain why the final print in main is allowed and whether either
call transfers ownership of the original String.
2. Return a borrowed view without the outer quotes
Write a function named unquote. It receives text surrounded by ASCII double quotes
and returns a borrowed view with exactly the first and last quote removed. Preserve every byte
between them, including any additional quote characters.
- Assume the input always starts and ends with
"and contains at least those two bytes. You do not need to validate malformed input or interpret escape sequences. - Return a view of the existing bytes. Do not allocate a new string, clone the input, or modify it.
- In
main, create an owned String whose contents are"report.txt", including the two quote characters. Call your function and print its result. - Print the original String afterward to demonstrate that it still contains the quotes.
Expected output:
unquoted: report.txt
original: "report.txt"
Check these inputs too. The source-code column distinguishes quote characters in the data
from the quotes that delimit a Rust literal. The first input contains two quote characters;
the Rust literal "" alone would contain zero characters.
| Input contents | Rust literal for input | Returned contents |
|---|---|---|
"" | "\"\"" | Empty text |
"a" | "\"a\"" | a |
"café" | "\"café\"" | café |
""a"" | "\"\"a\"\"" | "a" |
Syntax reminders, if needed
&text[start..end] borrows a range of bytes; the end position is excluded.
text.len() returns the byte length. String slice boundaries must lie between
complete UTF-8 characters. The outer ASCII quotes each occupy one byte.
The Rust Book: string slices.
As in C, \" inside a normal string literal represents one double-quote character.
With one borrowed input and a returned view, Rust can infer the lifetime relationship;
you do not need explicit lifetime annotations for this exercise.
For review: identify the owner of the returned text, and explain whether the returned view can remain usable after that owner is dropped.