11 rust async-await rust-cargo rust-tokio
我正在我的 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(())
}
Run Code Online (Sandbox Code Playgroud)
我的 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"
Run Code Online (Sandbox Code Playgroud)
当我执行时cargo run,显示以下错误:
[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"
Run Code Online (Sandbox Code Playgroud)
我从 Cargo.toml 文件中进行了交叉检查,并且edition = "2018"已经在那里了。我无法弄清楚其他错误。
She*_*ter 37
如文档中所述tokio::main:
仅适用于板条箱功能
rtmacros。
您需要添加这些功能才能访问tokio::main:
[dependencies]
tokio = { version = "1", features = ["rt", "macros"] }
Run Code Online (Sandbox Code Playgroud)
但是,这将只允许访问单线程执行程序,因此您必须使用#[tokio::main(flavor = "current_thread")]. 如果你想使用#[tokio::main](与 相同#[tokio::main(flavor = "multi_thread")],那么你需要启用多线程执行器:
仅适用于板条箱功能
rt-multi-thread。
[dependencies]
tokio = { version = "1", features = ["rt-multi-thread", "macros"] }
Run Code Online (Sandbox Code Playgroud)
也可以看看:
Ros*_*hur 17
您需要启用额外的功能tokio才能使用tokio::main.
尝试将该full功能添加到tokioCargo.toml 文件中的依赖项:
[dependencies]
tokio = { version = "0.2.22", features = ["full"] }
Run Code Online (Sandbox Code Playgroud)
这也适用于更高版本的 Tokio。
| 归档时间: |
|
| 查看次数: |
4468 次 |
| 最近记录: |