我正在我的 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 { …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用hyper来获取HTML页面的内容,并希望同步返回将来的输出。我意识到我可以选择一个更好的示例,因为同步HTTP请求已经存在,但是我对了解我们是否可以从异步计算中返回一个值更感兴趣。
extern crate futures;
extern crate hyper;
extern crate hyper_tls;
extern crate tokio;
use futures::{future, Future, Stream};
use hyper::Client;
use hyper::Uri;
use hyper_tls::HttpsConnector;
use std::str;
fn scrap() -> Result<String, String> {
let scraped_content = future::lazy(|| {
let https = HttpsConnector::new(4).unwrap();
let client = Client::builder().build::<_, hyper::Body>(https);
client
.get("https://hyper.rs".parse::<Uri>().unwrap())
.and_then(|res| {
res.into_body().concat2().and_then(|body| {
let s_body: String = str::from_utf8(&body).unwrap().to_string();
futures::future::ok(s_body)
})
}).map_err(|err| format!("Error scraping web page: {:?}", &err))
});
scraped_content.wait()
}
fn read() {
let scraped_content = future::lazy(|| {
let https = HttpsConnector::new(4).unwrap(); …Run Code Online (Sandbox Code Playgroud) 我正在尝试创建最简单的示例,async fn hello()最终可以打印出Hello World!. 这应该在没有任何外部依赖的情况下发生tokio,就像普通的 Rust 和std. 如果我们可以在不使用unsafe.
#![feature(async_await)]
async fn hello() {
println!("Hello, World!");
}
fn main() {
let task = hello();
// Something beautiful happens here, and `Hello, World!` is printed on screen.
}
Run Code Online (Sandbox Code Playgroud)
async/await这仍然是一个夜间功能,在可预见的未来可能会发生变化。Future实现,我知道tokio.我模糊的理解是,首先,我需要完成Pin任务。所以我继续前进
let pinned_task = Pin::new(&mut task);
Run Code Online (Sandbox Code Playgroud)
但
the trait `std::marker::Unpin` is not implemented for `std::future::GenFuture<[static generator@src/main.rs:7:18: 9:2 {}]>`
Run Code Online (Sandbox Code Playgroud)
所以我想,当然,我可能需要Box它,所以我确定它不会在内存中移动。有点令人惊讶的是,我得到了同样的错误。
到目前为止我能得到的是 …