相关疑难解决方法(0)

如何在稳定的Rust中同步返回在异步Future中计算的值?

我正在尝试使用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)

future rust hyper

6
推荐指数
1
解决办法
2698
查看次数

如何处理 HashMap 中的每个值并选择性地拒绝一些值?

我想HashMap一一处理这些值,同时可能会删除其中的一些值。

例如,我想做一个相当于:

use std::collections::HashMap;

fn example() {
    let mut to_process = HashMap::new();
    to_process.insert(1, true);

    loop {
        // get an arbitrary element
        let ans = to_process.iter().next().clone(); // get an item from the hash
        match ans {
            Some((k, v)) => {
                if condition(&k,&v) {
                    to_process.remove(&k);
                }
            }
            None => break, // work finished
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

但这无法编译:

error[E0502]: cannot borrow `to_process` as mutable because it is also borrowed as immutable
  --> src/lib.rs:12:17
   |
9  |         let ans = to_process.iter().next().clone();
   | …
Run Code Online (Sandbox Code Playgroud)

rust borrow-checker

3
推荐指数
1
解决办法
193
查看次数

标签 统计

rust ×2

borrow-checker ×1

future ×1

hyper ×1