http - 错误:在 tokio 中找不到 main 或 io,无效的返回类型`impl Future`
问题描述
我正在从 ML 家族转换到 Rust,但我发现在一些我不习惯遇到问题的奇怪地方很难。
我正在尝试使用hyper
http 处理,但似乎无法开始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
找不到: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
在超?
解决方案
该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"] }
您还需要超级client
和http
功能标志来解析Client
导入:
hyper = { version = "0.14.4", features = ["client", "http1", "http2"] }
推荐阅读
- html - 是否可以仅在仅使用 html 或 css 检查单选按钮后启用选择输入?
- css - 在多语言网站中使用 BEM 管理特异性
- javascript - JavaScript:在移动设备上隐藏 div
- asp.net - 每次我回来时我的网站都会注销
- python - 我的程序真的很简单,但我的 fps 增加不超过 20
- jquery - Angular 6 JQuery嵌套属性单击事件不起作用
- tensorflow - 如何将自定义渐变摘要添加到 tf.keras.callbacks.TensorBoard
- html - 如何在 index.html 以外的文件中重用这个导航栏 React 组件?
- python - 调整seaborn散点图中不同类别的不同透明度
- c# - 在运行时添加和删除 Grid 行