我正准备从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
类型,并且在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
是不是太夸张了?
发布于 2021-02-26 14:52:32
tokio::main
宏将async 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"] }
https://stackoverflow.com/questions/66387827
复制相似问题