2020-08-27
1731
#rust
Thomas Heartman
23920
Aug 27, 2020 â‹… 6 min read

Understanding lifetimes in Rust

Thomas Heartman Developer, speaker, musician, and fitness instructor.

Recent posts:

Exploring The Top Rust Web Frameworks

Exploring the top Rust web frameworks

In this article, we’ll explore the best Rust frameworks for web development, including Actix Web, Rocket, Axum, warp, Leptos, Cot, and Loco.

Abiodun Solomon
May 28, 2025 â‹… 11 min read
How To Use The CSS Cursor Property

How to use the CSS cursor property

A single line of CSS can change how users feel about your UI. Learn how to leverage the cursor property to signal intent, improve interaction flow, and elevate accessibility.

Chizaram Ken
May 28, 2025 â‹… 6 min read
Build TypeScript App Vite

How to build a React + TypeScript app with Vite

We explore the benefits of building an app with React, TypeScript, and Vite, and compare its performance to the same app built with CRA.

Clara Ekekenta
May 28, 2025 â‹… 7 min read

How to use Claude to build a web app

Learn how to build a weather app using Claude, from setting up infrastructure to creating a functional UI that displays city-based forecasts.

Andrew Evans
May 28, 2025 â‹… 8 min read
View all posts

2 Replies to "Understanding lifetimes in Rust"

  1. You write: “Lifetimes are what the Rust compiler uses to keep track of how long references are valid for.” But what about keeping track of which objects are borrowed? If I have a function f with signature fn f(x: &’a i32) -> &’a i32; and I do let x = 0; let y = f(&x); then rust borrow checker will consider y to be borrowing x . I don’t get this.

  2. Hey! Thanks for the question. Let me try and answer it for you.

    > How does the compiler keep track of which objects are borrowed?

    Any reference is a borrow. Whenever you have a value that’s not the owned instance, you have a borrow. In other words, keeping track of borrows is the same as keeping track of references. Declaring references (and lifetimes) in function signatures helps the compiler get the information it needs to keep track of borrows.

    > Why is `y` borrowing `x`?

    In your example, the function `f` takes a reference and returns the same reference. You then assign `y` to that reference. In other words, `y` is an `&i32`, while x is an `i32`. Because every reference is a borrow, ‘`y` borrows `x`’.

    Does that answer your questions?

Leave a Reply