1

Rust is complaining that get_string does not live long enough. It seems to want to stay alive for the whole function scope but I can't see how that happens.

error: `get_string` does not live long enough
  --> src\lib.rs:7:23
   |
7  |     for value_pair in get_string.split('&') {
   |                       ^^^^^^^^^^ does not live long enough
...
19 | }
   | - borrowed value only lives until here
   |
note: borrowed value must be valid for the anonymous lifetime #1 defined on the body at 3:59...
  --> src\lib.rs:3:60
   |
3  | fn parse_get(get_string: &str) -> HashMap<&str, Vec<&str>> {
   |                                                            ^

use std::collections::HashMap;

fn parse_get(get_string: &str) -> HashMap<&str, Vec<&str>> {
    let get_string = String::from(get_string);
    let mut parameters: HashMap<&str, Vec<&str>> = HashMap::new();

    for value_pair in get_string.split('&') {
        let name = value_pair.split('=').nth(0).unwrap();
        let value = value_pair.split('=').nth(1).unwrap();

        if parameters.contains_key(name) {
            parameters.get_mut(name).unwrap().push(value);
        } else {
            parameters.insert(name, vec![value]);
        }
    }

    parameters
}
Peter Hall
  • 53,120
  • 14
  • 139
  • 204
Brady Dean
  • 3,378
  • 5
  • 24
  • 50
  • 2
    You're trying to return references to a local variable; the local variable does not live long enough to return a reference to _because_ it's local... – ildjarn Apr 16 '17 at 01:19
  • 1
    Basically a duplicate of [Is there any way to return a reference to a variable created in a function?](http://stackoverflow.com/q/32682876/155423) – Shepmaster Apr 16 '17 at 12:24

1 Answers1

4

You are copying the input &str here:

let get_string = String::from(get_string);

This copy is owned by the function and will be dropped when the function finishes, but you are also returning a HashMap which contains references to it. It should be clear why that won't work.

Removing that one line will actually fix the error because you will then be referencing the function's argument instead.

Peter Hall
  • 53,120
  • 14
  • 139
  • 204