如何解决错误:在 tokio 中找不到 main 或 io,无效的返回类型 `impl Future`
我正在从 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
板条箱,并且 main
的类型无效 impl Future
,并且它找不到 main
tokio
:
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 中吗?
解决方法
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 的 client
和 http
功能标志来解析 Client
导入:
hyper = { version = "0.14.4",features = ["client","http1","http2"] }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。