rust - 找不到 tokio::main 宏?
问题描述
我正在我的 Windows 系统中创建一个示例 Rust 项目,以通过 HTTP GET 请求以异步模式下载文件。
我的代码如下(与Rust Cookbook 中提到的代码相同):
extern crate error_chain;
extern crate tempfile;
extern crate tokio;
extern crate reqwest;
use error_chain::error_chain;
use std::io::copy;
use std::fs::File;
use tempfile::Builder;
error_chain! {
foreign_links {
Io(std::io::Error);
HttpRequest(reqwest::Error);
}
}
#[tokio::main]
async fn main() -> Result<()> {
let tmp_dir = Builder::new().prefix("example").tempdir()?;
let target = "https://www.rust-lang.org/logos/rust-logo-512x512.png";
let response = reqwest::get(target).await?;
let mut dest = {
let fname = response
.url()
.path_segments()
.and_then(|segments| segments.last())
.and_then(|name| if name.is_empty() { None } else { Some(name) })
.unwrap_or("tmp.bin");
println!("file to download: '{}'", fname);
let fname = tmp_dir.path().join(fname);
println!("will be located under: '{:?}'", fname);
File::create(fname)?
};
let content = response.text().await?;
copy(&mut content.as_bytes(), &mut dest)?;
Ok(())
}
我的 Cargo.toml 文件是:
[package]
name = "abcdef"
version = "0.1.0"
authors = ["xyz"]
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
error-chain = "0.12.4"
tempfile = "3.1.0"
tokio = "0.2.22"
reqwest = "0.10.8"
当我执行cargo run
时,显示以下错误:
error[E0433]: failed to resolve: could not find `main` in `tokio`
--> src\main.rs:18:10
|
18 | #[tokio::main]
| ^^^^ could not find `main` in `tokio`
error[E0277]: `main` has invalid return type `impl std::future::Future`
--> src\main.rs:19:20
|
19 | async fn main() -> Result<()> {
| ^^^^^^^^^^ `main` can only return types that implement `
std::process::Termination`
|
= help: consider using `()`, or a `Result`
error[E0752]: `main` function is not allowed to be `async`
--> src\main.rs:19:1
|
19 | async fn main() -> Result<()> {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `main` function is not allowed to be `async`
我从 Cargo.toml 文件中进行了交叉检查,并且edition = "2018"
已经在那里。我无法弄清楚其他错误。
解决方案
您需要启用一个额外的功能tokio
才能使用tokio::main
.
尝试将该full
功能添加到tokio
Cargo.toml 文件中的依赖项中:
[dependencies]
tokio = { version = "0.2.22", features = ["full"] }
这也适用于 Tokio 的更高版本。
推荐阅读
- spring-boot - java中的速率限制和节流
- excel - 如何在Excel中复制具有特定列的所有行?
- tags - 当端点按标签重新分组时,如何访问 api.mustache 中有关导入的供应商扩展
- arm-template - 函数 - AzureWebJobsServiceBus 设置为来自在同一 ARM 模板中创建的规则的键
- python - 如何将 QFileDialog.getOpenFileNames 中的文件路径分配给可以在类外调用的变量?
- recursion - 如何使用递归迭代器展平递归结构?
- php - 如何解决“传递给 a 的参数 1 必须是 Bundle\Entity\.. 的实例,Doctrine\Common\Collections\ArrayCollection 给定的实例”?
- php - 如何在 laravel 中使用偏移和限制
- tarantool - tarantool 中有排序集功能吗?
- php - 如何使用 array_search 从数组中的多个值中搜索值