值要在整个函数范围内存在

Value wants to live for whole function scope

Rust 抱怨 get_string 活得不够长。它似乎想在整个功能范围内保持活力,但我看不出这是怎么发生的。

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
}

您正在此处复制输入&str

let get_string = String::from(get_string);

此副本归函数所有,函数完成后将被删除,但您还返回了一个 HashMap,其中包含对它的引用。应该清楚为什么那行不通。

删除这一行实际上会修复错误,因为您将改为引用函数的参数。