如何修复此终身问题?

时间:2016-06-05 06:26:17

标签: rust hyper

在下面的代码中,stringInto<Body<'a>>的{​​{1}}实施中的活动时间不够长。我理解为什么,因为RequestParameters<'a>进入string范围内,并且在方法完成后不再在范围内,但into会保留对它的引用。

至少,这就是为什么我认为Body<'a>的持续时间不够长。

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

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

如果我错误地说"?a=b"为什么活得不够久,请告诉我。我还在努力解决Rust中的终生系统问题,所以搞清楚这一点对我来说有点帮助。

string

1 个答案:

答案 0 :(得分: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);
}

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

相关问题