Rust代码编译中的一些奇怪问题

问题描述

我正在Windows系统中创建一个示例Rust项目,以异步方式通过HTTP GET请求下载文件

我的代码如下(与https://rust-lang-nursery.github.io/rust-cookbook/web/clients/download.html的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`

error: aborting due to 3 prevIoUs errors

我从Cargo.toml文件中进行了交叉检查,并且edition = "2018"已经存在。
而且,我无法找出其他错误

解决方法

tokio::main 的文档中所述:

这仅在板条箱功能 rtmacros 上受支持。

您需要添加这些功能才能访问 tokio::main

[dependencies]
tokio = { version = "1",features = ["rt","macros"] }

不过,这将只允许访问 the single-threaded executor,因此您必须使用 #[tokio::main(flavor = "current_thread")]。如果要使用#[tokio::main](与#[tokio::main(flavor = "multi_thread")]相同,则需要启用multi-threaded executor

仅在板条箱功能 rt-multi-thread 上支持此功能。

[dependencies]
tokio = { version = "1",features = ["rt-multi-thread","macros"] }

另见:

,

您需要在tokio中启用其他功能才能使用tokio::main

尝试将full功能添加到Cargo.toml文件中的tokio依赖项中:

[dependencies]
tokio = { version = "0.2.22",features = ["full"] }