为什么 get 方法在 reqwest 中不返回 Response 对象?

Why get method is not returning a Response object in reqwest?

我正在尝试从 reqwest documentation 复制一个示例。这是示例:

let body = reqwest::get("https://www.rust-lang.org")?
.text()?;

在文件 Cargo.toml 中添加 reqwest = "0.10.10" 行后,我在 main.rs 文件中添加以下代码:

extern crate reqwest;

fn main() {
    let body = reqwest::get("https://www.rust-lang.org")?.text()?;
    println!("body = {:?}", body);
}

此代码无法编译并且returns出现以下错误:

cannot use the `?` operator in a function that returns `()`

我对这种行为感到有点惊讶,因为我的代码几乎是 ipsis litteris 文档代码。

我认为 ? 仅适用于 Response 对象,所以我检查了 get 方法返回的对象:

extern crate reqwest;

fn print_type_of<T>(_: &T) {
    println!("{}", std::any::type_name::<T>())
}

fn main() {
    let body = reqwest::get("https://www.rust-lang.org");
    print_type_of(&body);
}

输出:

core::future::from_generator::GenFuture<reqwest::get<&str>::{{closure}}

我的意思是,为什么我没有像文档中那样得到 Response 对象?

您可能想阅读 Rust 文档的这一部分:https://doc.rust-lang.org/edition-guide/rust-2018/error-handling-and-panics/index.html

简而言之,? 只是通过隐式 return 将来自 Result 的错误传递到调用堆栈的更上层。因此,您使用 ? 运算符的函数必须 return 与使用 ? 的函数的类型相同。

这里有两个不同的问题让您感到困惑。

您链接到的文档适用于 reqwest 版本 0.9.18,但您安装的是版本 0.10.10。如果您查看 the docs for 0.10.10,您会发现您使用的代码段是

let body = reqwest::get("https://www.rust-lang.org")
    .await?
    .text()
    .await?;

println!("body = {:?}", body);

或者更可能是你的情况,因为你没有提到有一个异步运行时,the blocking docs

let body = reqwest::blocking::get("https://www.rust-lang.org")?
    .text()?;

println!("body = {:?}", body);

请注意,当您尝试使用这个时,您将仍然得到那个

cannot use the ? operator in a function that returns ()

并且您需要在 main 上设置一个 return 类型,例如

fn main() -> Result<(), reqwest::Error> {

有关详细信息,请参阅