capypad
0 day streak
rust / beginner
Snippet

Borrowing References with &

The ampersand symbol creates a reference to a value, allowing you to borrow it without taking ownership. References are immutable by default. String slices are created using the range syntax with &.

snippet.rs
rust
1
2
3
4
5
6
7
8
9
fn main() {
let value = 42;
let reference = &value;
println!("Value: {}, Reference: {}", value, reference);
let text = String::from("Hello Rust");
let slice = &text[0..5];
println!("String: {}, Slice: {}", text, slice);
}
Breakdown
1
let reference = &value;
Borrows value without taking ownership
2
let slice = &text[0..5];
Creates a string slice from index 0 to 5