Lifetimes

Contents
Elision covers most
One named lifetime (&'a form)
Static strings
Read compiler hints

Elision covers most

Most functions need no lifetime names because the compiler fills them in. A function that takes one shared borrow and returns one shared borrow just works:

fn first(s: &str) -> &str { s }

One named lifetime (&'a form)

When two borrows enter and one borrow leaves, name the relationship once. Both inputs and the output share the same name to show they live together:

fn longest(x: &'a str, y: &'a str) -> &'a str { if x.len() > y.len() { x } else { y } }

Static strings

String literals live for the whole program and use the static lifetime. A static borrow never expires while the program runs:

let s: &'static str = "hello";

Read compiler hints

When a lifetime is missing, the compiler suggests one exact spot to add it. Read the hint, add the name, and keep the change small:

let s = String::from("hi"); let r = s.as_str(); println!("{}", r);

Next: Functions

Article author: Arthur Isaev

Related articles
Rust
Rust course: zero to hero in 50 lessons
What is Rust and where it runs
Install Rust
cargo new
Your first program
Variables
Numbers
Strings
Booleans
Tuples
Arrays
Vectors
Slices
if and else
match
Loops
Ownership
Borrowing
Lifetimes
Functions
Structs
Enums in Rust
Advanced match in Rust
Option combinators in Rust
Result and the question mark in Rust
Advanced strings in Rust
Vec methods in Rust
HashMaps in Rust
Modules in Rust
Crates and workspaces in Rust
Testing in Rust
Error handling
Traits
Generics
Trait bounds
Closures
Iterators
Smart pointers
Threads
Mutex and Arc
Files
CLI arguments
Environment variables
Diagnostics
Time
Parsing strings
TCP networking
Capstone: wordfreq CLI
Capstone: tiny HTTP server
Modern Rust tour
Hero roadmap: the whole course on one page
Install Rust on Windows 11
Install Rust on Ubuntu
Install Rust on Rocky Linux
Install Rust on macOS
Install Rust on FreeBSD
Rust in Docker

Search this site

Channel @aofeed Chat @aofeedchat

Contacts and cooperation:
I recommend our hosting beget.com
Write to info@aredel.com if you:
1. Want to write an article for our site or translate an article into your native language.
2. Want to place thematically relevant ads on the site.
3. Ads on my site pass maximum censorship. If you see an ad block unsuitable for school-age children, shocking or misleading - please contact us by e-mail
4. Found a mistake, inaccuracy, bug, etc. on the site. ... .......
5. Articles can be shared on social media by clicking a network icon: