首页 文章

如何修复此终身问题?

提问于
浏览
0

在下面的代码中, stringInto<Body<'a>>Into<Body<'a>> 实现中的活动时间不够长 . 我理解为什么,因为 string 进入 into 范围内,并且在方法结束后不再在范围内,但 Body<'a> 将保留对它的引用 .

至少,这就是为什么我认为 string 的持续时间不够长 .

我不明白的是如何构造此代码来修复 string 的生命周期 .

此代码的目标是将HashMap(例如 "a""b" )转换为POST请求正文的字符串(例如, "?a=b" ) . 如果有更好的方法来做到这一点,请告诉我,但我会从中获益很多是了解如何解决这个生命周期问题 .

如果我错了为什么 string 仍然没有想要掌握Rust中的终生系统,那么搞清楚这一点对我来说会有所帮助 .

struct RequestParameters<'a> {
    map: HashMap<&'a str, &'a str>,
}

impl<'a> From<HashMap<&'a str, &'a str>> for RequestParameters<'a> {
    fn from(map: HashMap<&'a str, &'a str>) -> RequestParameters<'a> {
        RequestParameters { map: map }
    }
}

impl<'a> Into<Body<'a>> for RequestParameters<'a> {
    fn into(self) -> Body<'a> {
        let string = String::from("?") +
                     &self.map
            .iter()
            .map(|entry| format!("&{}={}", entry.0, entry.1))
            .collect::<String>()[1..];
        (&string).into()
    }
}

fn main() {
    let mut parameters = HashMap::new();
    parameters.insert("a", "b");
    let client = Client::new();
    client.post("https://google.com")
        .body(RequestParameters::from(parameters));
}

1 回答

  • 0

    正如弗拉基米尔的链接指出的那样,这实际上是不可能的 . 我改变了我的代码以反映这些知识,现在它编译了 .

    struct RequestParameters<'a> {
        map: HashMap<&'a str, &'a str>,
    }
    
    impl<'a> From<HashMap<&'a str, &'a str>> for RequestParameters<'a> {
        fn from(map: HashMap<&'a str, &'a str>) -> RequestParameters<'a> {
            RequestParameters { map: map }
        }
    }
    
    impl<'a> RequestParameters<'a> {
        fn to_string(self) -> String {
            String::from("?") +
            &self.map.iter().map(|entry| format!("&{}={}", entry.0, entry.1)).collect::<String>()[1..]
        }
    }
    
    fn main() {
        let mut parameters = HashMap::new();
        parameters.insert("a", "b");
        let string_parameters = RequestParameters::from(parameters).to_string();
        let client = Client::new();
        client.post("https://google.com")
            .body(&string_parameters);
    }
    

    通过在 Client 之前创建 String ,我可以使用比_2860844更长的生命周期来借用它,这可以解决我的问题 .

相关问题