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:

Nx Adoption Guide: Overview, Examples, And Alternatives

Nx adoption guide: Overview, examples, and alternatives

Let’s explore Nx features, use cases, alternatives, and more to help you assess whether it’s the right tool for your needs.

Andrew Evans
Mar 28, 2024 â‹… 9 min read
Understanding Security In React Native Applications

Understanding security in React Native applications

Explore the various security threats facing React Native mobile applications and how to mitigate them.

Wisdom Ekpotu
Mar 27, 2024 â‹… 10 min read
Warp Adoption Guide: Overview, Examples, And Alternatives

warp adoption guide: Overview, examples, and alternatives

The warp web framework for Rust offers many enticing features. Let’s see when and why you should consider using warp in your projects.

Ukeje Goodness
Mar 26, 2024 â‹… 8 min read
Integrating Next Js And Signalr For Enhanced Real Time Web App Capabilities

Integrating Next.js and SignalR to build real-time web apps

In this tutorial, you’ll learn how to integrate Next.js and SignalR to build an enhanced real-time web application.

Clara Ekekenta
Mar 25, 2024 â‹… 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