gpt4 book ai didi

rust - 解决 future 的元组

转载 作者:行者123 更新时间:2023-11-29 08:08:33 25 4
gpt4 key购买 nike

在 Rust 中,我试图通过使用 super 客户端作为元组从 .get 请求中提取两位数据来实现 future 。问题是生成的类型不起作用

所以给定一些这样的代码:

let result = client
.get(url)
.map_err(|err| Error::from(err))
.and_then(|response| {
(response
.into_body()
.concat2()
.map(|body| String::from_utf8(body.to_vec()).unwrap())
.map_err(|err| Error::from(err)),
response
.headers()
.get(CONTENT_TYPE)
.map(|content_type| content_type.to_str()))
});

我收到一个错误,例如the trait "futures::IntoFuture"is not implemented for...

我很确定这是因为元组的两个成员是 future 并且可以处理,但元组不是,但我不确定如何解决 future 的值(value)并将它们放入元组。

最佳答案

你的元组的第一个元素是一个 future ,但第二个元素是一个Option。虽然 IntoFuture 是为元组实现的,但只要所有元素都实现它并且错误类型匹配,您只有一个 future 要解决,因此有一个更简单的解决方案。

另一个问题是 response.into_body() 使用了 response,所以您以后无法访问它来检索 header 。由于我们只有一个 future 要解决,最简单的解决方案是先从响应中提取内容类型,然后将其附加到 map() 方法中的结果:

let result = client
.get("https://www.stackoverflow.com/".parse().unwrap())
.map_err(|err| Error::from(err))
.and_then(|response| {
let content_type = response
.headers()
.get(CONTENT_TYPE)
.map(|content_type| content_type.to_str().unwrap().to_string());
response
.into_body()
.concat2()
.map(|body| (
String::from_utf8(body.to_vec()).unwrap(),
content_type,
))
.map_err(|err| Error::from(err))
});

Full example code in the playground

如果您仍然无法使代码正常工作,我建议您发布一个问题,其中包括您尝试编译的实际代码的最小示例以及您收到的实际错误消息。使用 future 组合器的代码的错误消息可能会变得冗长且令人困惑,但它们仍然是了解代码为何无法编译的最重要的信息。

关于rust - 解决 future 的元组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52866443/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com