killtheverse
killtheverse

Reputation: 110

Rust: error: lifetime may not live long enough

I am new to rust. Whenever I try call this function, I get an error: lifetime may not live long enough. The error message further says that - argument requires that '1 must outlive '2.

fn get_sizes(dir: &str, listings: &HashMap<&str, Vec<Vec<&str>>>, sizes: &mut HashMap<&str, i32>){
    sizes.insert(dir, 0);
}

I want to set the value for key dir to 0 in hashmap sizes.

Upvotes: 4

Views: 4971

Answers (2)

jthulhu
jthulhu

Reputation: 8657

The problem is exactly what the compiler tells you (even though you did not put the whole message): the lifetime associated with the borrow of dir may be shorter than the one required by sizes. This is because the actual lifetimes are implicit, and all generic.

The solution is very simple: explicitly enforce equality of the lifetimes.

fn get_sizes<'a>(
    dir: &'a str,
    listings: &HashMap<&str, Vec<Vec<&str>>>,
    sizes: &mut HashMap<&'a str, i32>,
) {
    sizes.insert(dir, 0);
}

See the playground.

Upvotes: 2

cafce25
cafce25

Reputation: 27249

If you read the full error

error: lifetime may not live long enough
 --> src/lib.rs:3:5
  |
2 | pub fn get_sizes(dir: &str, _listings: &HashMap<&str, Vec<Vec<&str>>>, sizes: &mut HashMap<&str, i32>){
  |                       - let's call the lifetime of this reference `'1`                     - let's call the lifetime of this reference `'2`
3 |     sizes.insert(dir, 0);
  |     ^^^^^^^^^^^^^^^^^^^^ argument requires that `'1` must outlive `'2`
  |
help: consider introducing a named lifetime parameter
  |
2 | pub fn get_sizes<'a>(dir: &'a str, _listings: &HashMap<&str, Vec<Vec<&str>>>, sizes: &mut HashMap<&'a str, i32>){
  |                 ++++       ++                                                                      ++

You'll see that you have to enforce dir lives longer than the key in sizes with explicit lifetimes. Rust even gives you a suggested fix to that problem.

use std::collections::HashMap;
fn get_sizes<'a>(
    dir: &'a str,
    listings: &HashMap<&str, Vec<Vec<&str>>>,
    sizes: &mut HashMap<&'a str, i32>,
) {
    sizes.insert(dir, 0);
}

Upvotes: 1

Related Questions