-1

I am adding some elements to map in a function in rust

let mut my_map: HashMap<&str, &[u8] = HashMap::new();

for (key, value) in other_map {
   let some_string = format!("{} - ", value);
   my_map.insert(key, {some_str.as_bytes()};
}

Here i get the following error

error[E0597]: `processed_str` does not live long enough
  --> src\main.rs:21:37
   |
21 |         url_to_get_map.insert(key, {processed_str.as_bytes()});
   |         ----------------------------^^^^^^^^^^^^^^^^^^^^^^^^--
   |         |                           |
   |         |                           borrowed value does not live long enough
   |         borrow later used here
22 |     }
   |     - `processed_str` dropped here while still borrowed

How do i fix this?

Herohtar
  • 4,958
  • 4
  • 31
  • 39
Vas
  • 134
  • 10
  • You can't borrow temporary variables. Your hashmap expects to borrow the array but the array only exists inside the for loop and will therefore live shorter than the hashmap. – Ted Klein Bergman May 20 '22 at 15:25
  • If you don't have a better owner in mind, you can use [`to_vec`](https://doc.rust-lang.org/std/primitive.slice.html#method.to_vec) to convert the borrowed slice into an owned vector and store *that* in your hashmap. It incurs a copy, but sometimes that's worth it for the simplicity. – Silvio Mayolo May 20 '22 at 15:26
  • You will need to make the hashmap own that string, either in its string form (`String`), or as a vector of bytes (`Vec`). – E_net4 - Krabbe mit Hüten May 20 '22 at 15:26
  • 1
    Nitpick: _"You can't borrow temporary variables."_ You _can_ but as with any other borrow only as long as the temporary lives. (Otherwise things like `&Some(foo)` wouldn't work.) – cdhowie May 20 '22 at 16:58

0 Answers0