References
- Rust course
- Beginner
- Lesson 48/115
- 4 min
Create references with the & operator.
References
A reference (&) gives access to a value without taking ownership; this is called borrowing. When a reference goes out of scope nothing is dropped, because it isn't the value's owner:
fn uzunluk(s: &String) -> usize {
s.len()
}
let ad = String::from("Ada");
let n = uzunluk(&ad); // lent out
println!("{ad} {n}"); // ad is still validReferences are immutable by default; a borrowed value can be read but not changed.
Many readers
There can be as many immutable references as you want at the same time; they all read the value safely:
let s = String::from("rust");
let r1 = &s;
let r2 = &s;
println!("{r1} {r2} {}", r1.len());References are dereferenced automatically (auto-deref): writing r1.len() is the same as (*r1).len(). To dereference explicitly use *: let n = 5; let r = &n; println!("{}", *r + 1);.
Practice Count vowels
Let fn sesli(s: &str) -> usize count the letters found in "aeıioöuü" (chars().filter(...).count()). For let k = String::from("programlama");, call sesli(&k) and print both k and the result.
Starter code
fn main() {
// buraya yaz
}Sample solution
fn sesli(s: &str) -> usize {
s.chars().filter(|c| "aeıioöuü".contains(*c)).count()
}
fn main() {
let k = String::from("programlama");
let n = sesli(&k);
println!("{} {}", k, n);
}Expected output
programlama 4
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Why doesn't <code>fn f(s: &String) { s.push('!'); }</code> compile?
- ! is an invalid char
- It compiles
- &String is an immutable reference; &mut String is needed Correct answer
- push doesn't exist on String
Explanation: Changing it requires both the variable to be mut and a &mut reference to be passed.
2 Lend it
let ad = String::from("Ada");
let n = uzunluk(____ad);
let ad = String::from("Ada");
let n = uzunluk(&ad);
Explanation: & creates a reference to the value; ownership isn't transferred.
3 Expression and meaning
| Term | Meaning |
|---|---|
&s |
Immutable reference |
*r |
Dereferencing |
r.len() |
Automatic dereference |
fn f(s: &String) |
A borrowing function |