gpt4 book ai didi

rust - 是否可以让 Future::and_then 有条件地返回不同的 future ?

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

<分区>

在我的代码的这个简化版本中,我想有时执行标记的行,有时不执行,可能会返回一个错误:

extern crate futures; // 0.1.26
extern crate hyper; // 0.12.25

use hyper::rt::{Future, Stream};
use std::str::FromStr;

struct MyStream {}

impl Stream for MyStream {
type Item = hyper::Uri;
type Error = ();

fn poll(&mut self) -> Result<futures::Async<Option<Self::Item>>, Self::Error> {
Ok(futures::Async::Ready(Some(
hyper::Uri::from_str("http://www.google.com/").unwrap(),
)))
}
}

fn main() {
let client = hyper::Client::new();
let futs = MyStream {}
.map(move |uri| {
client
.get(uri)
.and_then(|res| {
res.into_body().concat2() // <----------------
})
.map(|body| {
println!("len is {}.", body.len());
})
.map_err(|e| {
println!("Error: {:?}", e);
})
})
.buffer_unordered(2)
.for_each(|_| Ok(()));

hyper::rt::run(futs);
}

我想我可以用这样的东西替换这一行:

let do_i_want_to_get_the_full_page = true;
if do_i_want_to_get_the_full_page {
res.into_body().concat2().map_err(|_| ())
} else {
futures::future::err(())
}

因为 futures 的 Error 部分是相同的,所以 Item 部分可以推断出来。但是,它不起作用。我该怎么做?

这是我得到的错误:

error[E0308]: if and else have incompatible types
--> src/main.rs:31:25
|
28 | / if do_i_want_to_get_the_full_page {
29 | | res.into_body().concat2().map_err(|_| ())
| | ----------------------------------------- expected because of this
30 | | } else {
31 | | futures::future::err(())
| | ^^^^^^^^^^^^^^^^^^^^^^^^ expected struct `futures::MapErr`, found struct `futures::FutureResult`
32 | | }
| |_____________________- if and else have incompatible types
|
= note: expected type `futures::MapErr<futures::stream::Concat2<hyper::Body>, [closure@src/main.rs:29:59: 29:65]>`
found type `futures::FutureResult<_, ()>`

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