Lesson 2 of 61
Lesson Progress: 0%
Borrowing means passing a value by reference instead of transferring ownership. When a function takes &Tas a parameter, it borrows the value — it can read it but does not own it. After the function returns, the original variable is still valid because ownership was never moved. Borrowing avoids unnecessary cloning and allows functions to work with data without taking it over. This lesson shows how to write functions that borrow their arguments.
fn show(val: &i32) {
println!("{}", val);
}
fn main() {
let x = 5;
show(&x);
}Instructions
▼ ← Click the triangle to hide or reveal instructions.Task Incomplete
Editor Input:
Editor Output:
fn show(val: &i32) takes a reference to an i32.x when called with show(&x).val is a reference that can be read.show returns, x is still valid.5.fn show(msg: &String) {
println!("{}", msg);
}
fn main() {
let s = String::from("hi");
show(&s);
println!("{}", s);
}Instructions
▼ ← Click the triangle to hide or reveal instructions.Task Incomplete
Editor Input:
Editor Output:
fn show(msg: &String) borrows a String reference.show(&s), s is still usable because ownership was not moved.s directly would move ownership and make s invalid.hi.fn add(a: &i32, b: &i32) -> i32 {
*a + *b
}
fn main() {
let x = 3;
let y = 7;
println!("{}", add(&x, &y));
}Instructions
▼ ← Click the triangle to hide or reveal instructions.Task Incomplete
Editor Input:
Editor Output:
fn add(a: &i32, b: &i32) -> i32 borrows two values and returns a new one.*a + *b dereferences both references to compute the sum.x and y are not moved.i32 is owned by the caller.10.fn length(s: &String) -> usize {
s.len()
}
fn main() {
let word = String::from("Rust");
println!("{}", length(&word));
}Instructions
▼ ← Click the triangle to hide or reveal instructions.Task Incomplete
Editor Input:
Editor Output:
s.len() works directly on a &String because method calls auto-dereference.word, so word remains valid after the call.length can read the string but cannot modify it.usize, the length of the string.4.fn first(s: &String) -> &str {
&s[0..1]
}
fn main() {
let word = String::from("Hi");
println!("{}", first(&word));
}Instructions
▼ ← Click the triangle to hide or reveal instructions.Task Incomplete
Editor Input:
Editor Output:
&str) of the borrowed data.&s[0..1] creates a string slice of the first character.String is alive.H.fn print_both(a: &i32, b: &i32) {
println!("{}", a);
println!("{}", b);
}
fn main() {
let x = 1;
let y = 2;
print_both(&x, &y);
}Instructions
▼ ← Click the triangle to hide or reveal instructions.Task Incomplete
Editor Input:
Editor Output:
a and b are references passed to print_both.x and y are still valid.1 and 2 on separate lines.Test Incomplete