【问题标题】:reqwest example POST request not compiling [duplicate]reqwest 示例 POST 请求未编译 [重复]
【发布时间】:2020-10-13 11:29:55
【问题描述】:

我尝试遵循以下 reqwest 示例:

let client = reqwest::Client::new();
let res = client.post("http://httpbin.org/post")
    .body("the exact body that is sent")
    .send()?;

示例编译失败:

error[E0277]: the `?` operator can only be applied to values that implement `std::ops::Try`
  --> src/main.rs:26:15
   |
26 |       let res = client.post("http://httpbin.org/post")
   |  _______________^
27 | |     .body("the exact body that is sent")
28 | |     .send()?;
   | |____________^ the `?` operator cannot be applied to type `impl std::future::Future`
   |
   = help: the trait `std::ops::Try` is not implemented for `impl std::future::Future`
   = note: required by `std::ops::Try::into_result`

error[E0277]: the `?` operator can only be used in a function that returns `Result` or `Option` (or another type that implements `std::ops::Try`)
  --> src/main.rs:26:15
   |
11 |  / fn main(){
12 |  |     // gets the api key from env var
13 |  |     let mut key: String = env::var("key").unwrap();
14 |  |     // get the mok key bassically useless but its still useful to prevent tampering
...   |
26 |  |     let res = client.post("http://httpbin.org/post")
   |  |_______________^
27 | ||     .body("the exact body that is sent")
28 | ||     .send()?;
   | ||____________^ cannot use the `?` operator in a function that returns `()`
...   |
49 |  |     //}
50 |  | }
   |  |_- this function should return `Result` or `Option` to accept `?`
   |
   = help: the trait `std::ops::Try` is not implemented for `()`
   = note: required by `std::ops::Try::from_error`

我应该如何解决这个问题?这是过时了吗? 我正在使用 Rust 版本 1.47.0

【问题讨论】:

  • 如果你只是想编译它,你可以将编译器抱怨的?替换为.unwrap()
  • 不,这个例子并没有过时。它只要求将代码放在返回 Result 的函数中,这是示例代码的常见要求。
  • 添加展开会引发此错误no method named 'unwrap' found for opaque type 'impl std::future::Future' in the current scope
  • 此代码可能确实与您使用的 reqwest 版本不同。请转到 https://docs.rs/reqwest 上与您正在使用的版本相同的文档版本。
  • 使用reqwest::blocking::Client 代替reqwest::Client 可能会成功。

标签: rust reqwest


【解决方案1】:

根据错误消息,您使用的是异步版本的 reqwest。如果我没记错的话,最新版本包含异步和阻塞版本。

为了真正消费future并获得里面的值,你需要使用一个executor来执行它,例如东京。这可以通过多种方式完成。

最简单的方法是将 tokio = { version = "0.2.22", features = ["macros"] } 添加到您的 Cargo.toml 中,然后在 main.rs 中添加:

#[tokio::main]
async fn main() {
    let client = reqwest::Client::new();
    let res = client.post("http://httpbin.org/post")
        .body("the exact body that is sent")
        .send().await;
} 

请注意,我删除了 ?,因为未来不会解析为 ResultOption

【讨论】: