Brady Dean
Brady Dean

Reputation: 3573

Value wants to live for whole function scope

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
}

Upvotes: 1

Views: 91

Answers (1)

Peter Hall
Peter Hall

Reputation: 58875

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.

Upvotes: 4

Related Questions