Lesson 1 of 61
Lesson Progress: 0%
A reference in Rust lets you point to a value without taking ownership of it. You create an immutable reference with the & operator and access the referenced value with the dereference operator *. The original variable still owns its data and remains valid. You can create multiple references to the same value. Dereferencing happens automatically in many cases, such as inside println!. This lesson covers the basics of creating and using references.
fn main() {
let x = 5;
let r = &x;
println!("{}", r);
}Instructions
▼ ← Click the triangle to hide or reveal instructions.Task Incomplete
Editor Input:
Editor Output:
let x = 5; binds the value 5 to x.let r = &x; creates a reference r that points to x without taking ownership.r to println! automatically dereferences and prints 5.x still owns the value and can be used later.fn main() {
let x = 10;
let r = &x;
println!("{}", *r);
}Instructions
▼ ← Click the triangle to hide or reveal instructions.Task Incomplete
Editor Input:
Editor Output:
*r syntax explicitly dereferences the reference to get the value.println! can also print the reference directly because it knows how to display integers.i32 value.10.* is called the dereference operator.fn main() {
let x = 42;
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 &i32 references pointing to x.42 42.fn main() {
let s = String::from("hi");
let r = &s;
println!("{}", r);
}Instructions
▼ ← Click the triangle to hide or reveal instructions.Task Incomplete
Editor Input:
Editor Output:
String.let r = &s; borrows the String without moving it.s still owns the string data after the reference is created.hi.String have type &String.fn main() {
let x = 7;
let r = &x;
println!("{}", x);
println!("{}", r);
}Instructions
▼ ← Click the triangle to hide or reveal instructions.Task Incomplete
Editor Input:
Editor Output:
x is still valid and can be printed directly.r is a reference and prints the same value.x and r produce the output 7.fn main() {
let x = 3;
let r = &x;
let y = *r + 1;
println!("{}", y);
}Instructions
▼ ← Click the triangle to hide or reveal instructions.Task Incomplete
Editor Input:
Editor Output:
* to use the value in expressions.*r + 1 dereferences r to get 3, then adds 1.4 is stored in y.x remains unchanged.Test Incomplete