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:

How to display notification badges on PWAs using the Badging API

Ding! You got a notification, but does it cause a little bump of dopamine or a slow drag of cortisol? […]

Chigozie Oduah
Sep 13, 2024 â‹… 4 min read
JWT Authentication: Best Practices And When To Use It

JWT authentication: Best practices and when to use it

A guide for using JWT authentication to prevent basic security issues while understanding the shortcomings of JWTs.

Flavio Copes
Sep 12, 2024 â‹… 5 min read

Auth.js adoption guide: Overview, examples, and alternatives

Auth.js makes adding authentication to web apps easier and more secure. Let’s discuss why you should use it in your projects.

Clara Ekekenta
Sep 12, 2024 â‹… 10 min read
Lucia Auth: An Auth.js Alternative For Next.js Authentication

Lucia Auth: An Auth.js alternative for Next.js authentication

Compare Auth.js and Lucia Auth for Next.js authentication, exploring their features, session management differences, and design paradigms.

Paul Akinyemi
Sep 12, 2024 â‹… 4 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