gpt4 book ai didi

rust - 为什么get方法未在reqwest中返回Response对象?

转载 作者:行者123 更新时间:2023-12-03 11:41:29 65 4
gpt4 key购买 nike

我正在尝试从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);
}
此代码不会编译并返回以下错误:
cannot use the `?` operator in a function that returns `()`
我对这种行为感到有些惊讶,因为我的代码几乎是文档代码。
我认为 ?仅适用于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对象?

最佳答案

这里有两个单独的问题使您绊倒。
您链接到的文档是针对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上设置返回类型,例如
fn main() -> Result<(), reqwest::Error> {
有关更多信息,请参见 Why do try!() and ? not compile when used in a function that doesn't return Option or Result?

关于rust - 为什么get方法未在reqwest中返回Response对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65556721/

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