Lesson 3 of 61
Lesson Progress: 0%
An immutable (shared) reference &T allows reading a value but not modifying it. Many immutable references to the same data can exist at the same time. This makes immutable borrowing safe for concurrent reading. If you try to mutate through an immutable reference, the compiler will reject it. This lesson explores creating and using multiple immutable references.
fn main() {
let x = 5;
let r1 = &x;
let r2 = &x;
println!("{} {}", r1, r2);
}Instructions
▼ ← Click the triangle to hide or reveal instructions.Task Incomplete
Editor Input:
Editor Output:
r1 and r2 are created to the same x.5 5.fn read(a: &i32) {
println!("{}", a);
}
fn main() {
let x = 10;
read(&x);
read(&x);
}Instructions
▼ ← Click the triangle to hide or reveal instructions.Task Incomplete
Editor Input:
Editor Output:
&i32 parameter can be called multiple times on the same value.x without modifying it.10 printed twice.fn read(a: &i32, b: &i32) {
println!("{}", a + b);
}
fn main() {
let x = 3;
let y = 4;
read(&x, &y);
}Instructions
▼ ← Click the triangle to hide or reveal instructions.Task Incomplete
Editor Input:
Editor Output:
&x and &y are passed at the same time.a + b dereferences both references.7.fn print_len(s: &String) {
println!("{}", s.len());
}
fn main() {
let word = String::from("hello");
print_len(&word);
print_len(&word);
}Instructions
▼ ← Click the triangle to hide or reveal instructions.Task Incomplete
Editor Input:
Editor Output:
String can be immutably borrowed multiple times.print_len reads the length without modifying the string.word simultaneously.5 twice.word remains the owner after both calls.fn get_first(s: &String) -> &str {
&s[0..1]
}
fn main() {
let word = String::from("abc");
println!("{}", get_first(&word));
}Instructions
▼ ← Click the triangle to hide or reveal instructions.Task Incomplete
Editor Input:
Editor Output:
get_first borrows the string and returns a slice reference.&s[0..1] is valid as long as the original String exists.a.fn add_three(a: &i32, b: &i32, c: &i32) -> i32 {
*a + *b + *c
}
fn main() {
let x = 1;
let y = 2;
let z = 3;
println!("{}", add_three(&x, &y, &z));
}Instructions
▼ ← Click the triangle to hide or reveal instructions.Task Incomplete
Editor Input:
Editor Output:
*a + *b + *c dereferences each reference to compute the sum.6.Test Incomplete