【问题标题】:Error: Could not find main or io in tokio, invalid return type `impl Future`错误:在 tokio 中找不到 main 或 io,无效的返回类型`impl Future`
【发布时间】:2021-02-26 14:43:06
【问题描述】:

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

我正在尝试使用 hyper 进行 http 处理,但似乎无法让 tokio 工作。

我试图复制粘贴这个example

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 crate,mainimpl Future 类型无效,在tokio 中找不到main

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 不在 hyper 中吗?

【问题讨论】:

    标签: http rust hyper tokio


    【解决方案1】:

    tokio::main 宏将 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"] }
    

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

    hyper = { version = "0.14.4", features = ["client", "http1", "http2"] }
    

    【讨论】:

    • 谢谢.. 这很有帮助,尽管有 C++ 语法,但我喜欢 rust,这几乎是每一种语言使用的一个小麻烦。我认为它是大约 40 年来第一个实际上不仅仅是复制其他语言的语言,而是认真审视了语言理论和类型系统的进展,并决定是时候在一些帮助下制作一个新的 C把自己的脚射下来。它不支持 OO,但只有“OO like”是一个成功的论点。 OO 是仅有的没有带来任何东西的语言特性之一。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-27
    • 2015-02-08
    相关资源
    最近更新 更多