在像C#这样的语言中,给出这个代码(我没有await故意使用关键字):
async Task Foo()
{
var task = LongRunningOperationAsync();
// Some other non-related operation
AnotherOperation();
result = task.Result;
}
Run Code Online (Sandbox Code Playgroud)
在第一行中,long操作在另一个线程中运行,并Task返回a(即未来).然后,您可以执行另一个与第一个并行运行的操作,最后,您可以等待操作完成.我认为,这也是行为async/ await在Python,JavaScript等
另一方面,在Rust中,我在RFC中读到:
Rust的期货与其他语言的期货之间的根本区别在于,除非进行调查,否则Rust的期货不会做任何事情.整个系统是围绕这个建立的:例如,取消正在降低未来正是出于这个原因.相比之下,在其他语言中,调用异步fn会旋转一个立即开始执行的未来.
在这种情况下,是什么目的async/ await鲁斯特?看到其他语言,这种表示法是一种运行并行操作的便捷方式,但是如果调用async函数没有运行任何东西,我无法看到它在Rust中是如何工作的.
我正在尝试根据Option函数的输入切换行为.想法是基于给定Option是否存在来迭代.这是一个最小的,如果愚蠢的例子:
use std::iter;
fn main() {
let x: Option<i64> = None;
// Repeat x 5 times if present, otherwise count from 1 to 5
for i in match x {
None => 1..5,
Some(x) => iter::repeat(x).take(5),
} {
println!("{}", i);
}
}
Run Code Online (Sandbox Code Playgroud)
我收到一个错误:
error[E0308]: match arms have incompatible types
--> src/main.rs:7:14
|
7 | for i in match x {
| ______________^
8 | | None => 1..5,
9 | | Some(x) => iter::repeat(x).take(5),
| | …Run Code Online (Sandbox Code Playgroud) 我的客户通过Authorization标头中的令牌进行授权,每个请求都需要检查该令牌。如果没有这个头或者找不到对应的用户,我想返回HTTP代码Unauthorized,否则我想正常处理请求。
目前我有很多重复的代码,因为我正在每个请求处理程序中检查这个标头。该Actix的文档中的第一段表明,它是可能的halt request processing to return a response early。如何做到这一点?
由于我还没有找到实现此行为的示例,因此我尝试提出自己的中间件函数,但无法编译。
为了克服返回两种不同类型(ServiceResponse和Map)的问题,我已经对返回值进行了装箱,因此在如何有条件地返回不同类型的期货?不是问题。更重要的是,我不知道哪些类型具有哪些特征实现需要作为此wrap_fn函数的返回值。我现在拥有的那些不起作用。
App::new()
.wrap(Cors::new().allowed_origin("http://localhost:8080"))
.register_data(state.clone())
.service(
web::scope("/routing")
.wrap_fn(|req, srv| {
let unauth: Box<dyn IntoFuture<Item = ServiceResponse>> = Box::new(ServiceResponse::new(req.into_parts().0, HttpResponse::Unauthorized().finish()));
let auth_header = req.headers().get("Authorization");
match auth_header {
None => unauth,
Some(value) => {
let token = value.to_str().unwrap();
let mut users = state.users.lock().unwrap();
let user_state = users.iter_mut().find(|x| x.auth.token == token);
match user_state {
None => unauth,
Some(user) …Run Code Online (Sandbox Code Playgroud) 我想要一个随机数发生器.既然OsRng::new()可能会失败,我想回到以下情况,thread_rng()如果我必须:
extern crate rand; // 0.6.5
use rand::{rngs::OsRng, thread_rng, RngCore};
fn rng() -> impl RngCore {
match OsRng::new() {
Ok(rng) => rng,
Err(e) => thread_rng(),
}
}
Run Code Online (Sandbox Code Playgroud)
但是,我收到此错误消息,我无法理解:
error[E0308]: match arms have incompatible types
--> src/lib.rs:6:5
|
6 | / match OsRng::new() {
7 | | Ok(rng) => rng,
8 | | Err(e) => thread_rng(),
| | ------------ match arm with an incompatible type
9 | | }
| |_____^ expected struct `rand::rngs::OsRng`, found struct `rand::prelude::ThreadRng` …Run Code Online (Sandbox Code Playgroud) 我有 2 个返回相同类型的函数 impl Future<Item = (), Error = ()>
extern crate tokio;
extern crate futures;
use tokio::timer::Interval;
use std::time::{Duration, Instant};
use tokio::prelude::*;
use futures::future;
fn run2() -> impl Future<Item = (), Error = ()> {
future::ok(())
}
fn run() -> impl Future<Item = (), Error = ()> {
Interval::new(Instant::now(), Duration::from_millis(1000))
.for_each(move |instant| {
println!("fire; instant={:?}", instant);
Ok(())
})
.map_err(|e| panic!("interval errored; err={:?}", e))
}
fn main_run() -> impl Future<Item = (), Error = ()> {
if 1 == 1 …Run Code Online (Sandbox Code Playgroud) 我正在尝试异步调用Future从函数返回的 a 。是否可以?
use core::future::Future;
fn choose_your_adventure<'a>(i: usize) -> Box<&'a dyn Future<Output = ()>> {
match i {
0 => Box::new(&async {}),
_ => Box::new(&async {})
}
}
async fn does_not_work() -> () {
let choice = choose_your_adventure(0);
choice.await; // error[E0277]: `&dyn Future<Output = ()>` is not a future
}
Run Code Online (Sandbox Code Playgroud) rust ×6
async-await ×2
actix-web ×1
asynchronous ×1
future ×1
return-type ×1
rust-actix ×1
server ×1
syntax ×1
traits ×1