How to create mutable structures that live for the lifetime of the function from a smaller scope?

I am trying to a write a rust program that acquires data from multiple devices and saves them to an output file corresponding to each device.

The program works like this.

  • Spawn writer a thread in which we open a file corresponding to each device.
  • In this thread each opened mutable files is saved in a hashmap with device id as key.
  • When data arrives (device-id, data) pair; we get the output file corresponding to the device-id and write the data to it.

A minimum non-working example is here playground link.

I get life time errors such as temporary value is freed at the end of this statement etc.

I have tried to specify manual lifetimes but I could not seem to get past the different reincarnations of lifetime errors.

Any pointers will be much appreciated. :slight_smile:

I blindly fixed your playground by saving an owned File in the map rather than a mutable reference.

2 Likes

There may be some confusion here due to the word "lifetime". A Rust lifetime (those '_ things) as part of a type (like &'_ mut File) is typically describing the duration of a borrow. It it not describing the liveness scope of a value, like when something will be destructed.

Borrow checking is a pass-or-fail compile time check, and is not allowed to change the semantics of a program. So changing the annotated lifetimes in a Rust program cannot make values live longer.

If you want to keep a value alive, you're dealing with ownership. The way to make the File live for longer is to give ownership of it away to something that lasts longer (which is what @jofas has done).

(Rust references (&_, &mut) are borrows of what they point to, not owners.)

5 Likes

Thanks for the feedback and the fix.
I think I understand ownership and mutability a little better now. :beers:

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.