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:

Rxjs Adoption Guide: Overview, Examples, And Alternatives

RxJS adoption guide: Overview, examples, and alternatives

Get to know RxJS features, benefits, and more to help you understand what it is, how it works, and why you should use it.

Emmanuel Odioko
Jul 26, 2024 â‹… 13 min read
Decoupling Monoliths Into Microservices With Feature Flags

Decoupling monoliths into microservices with feature flags

Explore how to effectively break down a monolithic application into microservices using feature flags and Flagsmith.

Kayode Adeniyi
Jul 25, 2024 â‹… 10 min read
Lots of multi-colored blue and purplish rectangles.

Animating dialog and popover elements with CSS @starting-style

Native dialog and popover elements have their own well-defined roles in modern-day frontend web development. Dialog elements are known to […]

Rahul Chhodde
Jul 24, 2024 â‹… 10 min read
Using Llama Index To Add Personal Data To Large Language Models

Using LlamaIndex to add personal data to LLMs

LlamaIndex provides tools for ingesting, processing, and implementing complex query workflows that combine data access with LLM prompting.

Ukeje Goodness
Jul 23, 2024 â‹… 5 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