问题描述
我正在尝试从 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 `()`
我对这种行为感到有点惊讶,因为我的代码几乎是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 对象,就像文档一样?
解决方法
这里有两个不同的问题让您感到困惑。
您链接到的文档适用于 ^#Right::
send,^#{Right}
return
^#Left::
send,^#{Left}
return
版本 reqwest
,但您已经安装了 0.9.18
版本。如果您查看 the docs for 0.10.10
,您会看到您使用的代码段是
0.10.10
或者更可能在您的情况下,因为您没有提到有异步运行时,the blocking
docs
let body = reqwest::get("https://www.rust-lang.org")
.await?
.text()
.await?;
println!("body = {:?}",body);
注意,当你尝试使用这个时,你会仍然得到那个
不能在返回 let body = reqwest::blocking::get("https://www.rust-lang.org")?
.text()?;
println!("body = {:?}",body);
的函数中使用 ?
运算符
并且您需要在 ()
上设置返回类型,例如
main
有关详细信息,请参阅 Why do try!() and ? not compile when used in a function that doesn't return Option or Result?。
,您可能想阅读 Rust 文档的这一部分:https://doc.rust-lang.org/edition-guide/rust-2018/error-handling-and-panics/index.html
简而言之,?
只是通过隐式 Result
将错误从 return
进一步向上传递到调用堆栈。因此,您在其中使用 ?
运算符的函数必须返回与使用 ?
的函数相同的类型。