Summary - Lifetimes
- Rust course
- Intermediate
- Lesson 18/115
- 5 min
Write a function that returns the longest text using lifetime parameters.
Lifetimes summary
A lifetime is the region where a reference is valid; the compiler checks that a reference doesn't outlive its value. In most cases the three elision rules infer lifetimes. If several references go in and a reference comes out, the relationship is written explicitly with <'a>. Structs holding references take the form struct S<'a>. 'static is valid until the end of the program. A common fix for lifetime problems is returning an owned value.
Returning a piece of the text
Since there is a single reference parameter, the function below doesn't need a lifetime; but writing it explicitly is allowed too and improves readability by documenting the relationship:
fn en_uzun_kelime<'a>(metin: &'a str) -> &'a str {
metin
.split_whitespace()
.max_by_key(|k| k.chars().count())
.unwrap_or("")
}The returned word is a slice of the source; nothing is copied.
Practice Longest word
Write the en_uzun_kelime function above. Print the result for "Rust güvenli ve hızlı bir dildir".
Starter code
fn main() {
// buraya yaz
}Sample solution
fn en_uzun_kelime<'a>(metin: &'a str) -> &'a str {
metin
.split_whitespace()
.max_by_key(|k| k.chars().count())
.unwrap_or("")
}
fn main() {
println!("{}", en_uzun_kelime("Rust güvenli ve hızlı bir dildir"));
}Expected output
güvenli
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which element does <code>max_by_key</code> return when keys are equal?
- None
- The last one Correct answer
- The first one
- A random one
Explanation: According to the docs, max_by_key returns the last element on ties and min_by_key the first.
2 Largest by key
metin.split_whitespace().____(|k| k.chars().count())
metin.split_whitespace().max_by_key(|k| k.chars().count())
Explanation: max_by_key finds the largest element by the result of the given function.
3 Group summary
| Term | Meaning |
|---|---|
'a |
Lifetime parameter |
'static |
Whole program |
Elision |
Automatic inference |
S<'a> |
Struct holding a reference |