1

我正在从 ML 家族转换到 Rust,但我发现在一些我不习惯遇到问题的奇怪地方很难。

我正在尝试使用hyperhttp 处理,但似乎无法开始tokio工作。

我试图复制粘贴这个例子

use hyper::{body::HttpBody as _, Client};
use tokio::io::{self, AsyncWriteExt as _};

type Result<T> = std::result::Result<T, Box<dyn std::error::Error + Send + Sync>>;

#[tokio::main]
async fn main() -> Result<()> {
    // ...
    fetch_url(url).await
}


async fn fetch_url(url: hyper::Uri) -> Result<()> {
    // ...
    Ok(())
}

这是我的Cargo.toml

[package]
name = "projectname"
version = "0.1.0"
authors = ["username"]
edition = "2018"
    
[dependencies]
hyper = "0.14.4"
tokio = "1.2.0"

它抱怨找不到io箱子,并且main类型无效,并且在以下位置impl Future找不到:maintokio

error[E0433]: failed to resolve: could not find `main` in `tokio`
 --> src/main.rs:9:10
  |
9 | #[tokio::main]
  |          ^^^^ could not find `main` in `tokio`

error[E0277]: `main` has invalid return type `impl Future`
  --> src/main.rs:10:20
   |
10 | async fn main() -> Result<()> {
   |                    ^^^^^^^^^^ `main` can only return types that implement `Termination`

error[E0432]: unresolved import `hyper::Client`
 --> src/main.rs:3:34
  |
3 | use hyper::{body::HttpBody as _, Client};
  |                                  ^^^^^^ no `Client` in the root

error[E0425]: cannot find function `stdout` in module `io`
  --> src/main.rs:45:13
   |
45 |         io::stdout().write_all(&chunk).await?;
   |             ^^^^^^ not found in `io`
   |

error[E0432]: unresolved import `tokio::io::AsyncWriteExt`
 --> src/main.rs:4:23
  |
4 | use tokio::io::{self, AsyncWriteExt as _};
  |                       -------------^^^^^
  |                       |
  |                       no `AsyncWriteExt` in `io`
  |                       help: a similar name exists in the module: `AsyncWrite`

#[tokio::main]不是client在超?

4

1 回答 1

3

tokio::main宏将 an 转换async main为生成运行时的常规 main。但是,由于找不到宏是作用域,它无法转换您的 main 函数,并且编译器抱怨您的 main 具有无效的返回类型impl Future. 要解决此问题,您必须启用导入main宏所需的功能:

tokio = { version = "1.2.0", features = ["rt", "macros"] }

您还必须启用io-util要访问io::AsyncWriteExt的功能和要访问的io-std功能io::stdout。为了简化这一点,tokio提供了full功能标志,它将启用所有可选功能:

tokio = { version = "1.2.0", features = ["full"] }

您还需要超级clienthttp功能标志来解析Client导入:

hyper = { version = "0.14.4", features = ["client", "http1", "http2"] }
于 2021-02-26T14:52:32.660 回答