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:

Building a Full-Featured Laravel Admin Dashboard with Filament

Building a full-featured Laravel admin dashboard with Filament

Build scalable admin dashboards with Filament and Laravel using Form Builder, Notifications, and Actions for clean, interactive panels.

Kayode Adeniyi
Dec 20, 2024 â‹… 5 min read
Working With URLs In JavaScript

Working with URLs in JavaScript

Break down the parts of a URL and explore APIs for working with them in JavaScript, parsing them, building query strings, checking their validity, etc.

Joe Attardi
Dec 19, 2024 â‹… 6 min read
Lazy Loading Vs. Eager Loading

Lazy loading vs. Eager loading

In this guide, explore lazy loading and error loading as two techniques for fetching data in React apps.

Njong Emy
Dec 18, 2024 â‹… 5 min read
Deno logo over an orange background

How to migrate your Node.js app to Deno 2.0

Deno is a popular JavaScript runtime, and it recently launched version 2.0 with several new features, bug fixes, and improvements […]

Yashodhan Joshi
Dec 17, 2024 â‹… 7 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