< 返回版块

zjhken 发表于 2019-10-12 20:58

Tags:futures,future,函数签名,async fn,

以下代码无法编译通过, 原因是函数的类型表达不能用impl Trait

use std::process::Output;
use std::future::Future;

fn main(){
	let mut v: Vec<fn()->impl Future<Output=()>> = vec![];
	
	v.push(haha);
}

async fn haha(){
	println!("haha");
}

那么请教一下, 要怎么样改写vector的类型声明呢?

评论区

写评论
UkonnRa 2019-11-05 14:49

https://www.reddit.com/r/rust/comments/drtxbt/question_how_to_put_async_fn_into_a_map/f6lb4wt/ 目前为止最好的 workround 了

UkonnRa 2019-11-05 13:11

好像目前没办法做,不然 hyper/acitx-web 之类的就能实现异步 router 了,不过还是坐等大佬实现(反正这个问题我搞了两天,放弃了,rust 自己类型系统不全的问题)

fcbldopb 2019-11-02 22:50
use std::future::Future;
use std::pin::Pin;
fn main(){
	let mut v :Vec<Pin<Box<dyn Future<Output=()>>>>= vec![Box::pin(haha()),Box::pin(aaa())];
	
	
	//v.push(aaa);
	//v.push(1);
    print_type(&v);
	
}

async fn haha(){
	println!("haha");
}
async fn aaa(){
    
}
fn print_type<T>(_:&T){
    println!("{}",std::any::type_name::<T>());
}

1.vec![] 要求类型一致和编译时大小可知
2.类型一致: async 使用 Future ,Output= 应该和异步函数返回类型一致 3.编译时大小: 使用Box指针,因为指针大小是确定的32bit 或 64bit 4.因为async实现的原因,需要pin来禁止move

ywxt 2019-11-02 01:25

好像不行,因为rust对于每个async函数会实现future,然后函数签名就不同了。

use std::future::Future;
fn main(){
	let mut v = vec![haha,aaa];
	
	
	//v.push(aaa);
	//v.push(1);
    print_type(&v);
	
}

async fn haha(){
	println!("haha");
}
async fn aaa(){
    
}
fn print_type<T>(_:&T){
    println!("{}",std::any::type_name::<T>());
}

错误是

error[E0308]: mismatched types
 --> src/main.rs:3:24
  |
3 |     let mut v = vec![haha,aaa];
  |                           ^^^ expected opaque type, found a different opaque type
  |
  = note: expected type `fn() -> impl std::future::Future {haha}`
             found type `fn() -> impl std::future::Future {aaa}`
  = note: distinct uses of `impl Trait` result in different opaque types
  = help: if both `Future`s have the same `Output` type, consider `.await`ing on both of them
作者 zjhken 2019-10-13 10:51

感谢大佬!!!!! 不过在这里有个疑问, 我之前试了Vec<fn() -> Box<dyn Future<Output = ()>>, 但是不行,

  --> src\main.rs:18:21
   |
18 |     v.push(Box::new(haha));
   |                     ^^^^ expected struct `std::boxed::Box`, found opaque type
   |
   = note: expected type `fn() -> std::boxed::Box<dyn std::future::Future<Output = ()>>`
              found type `fn() -> impl std::future::Future {haha}`

说是"不透明类型", 所以fn()->()这种写法就是所谓的不透明类型吗? 是因为这种表示法不是大小固定的吗?

对以下内容的回复:

93996817 2019-10-13 00:19

async fn haha() { println!("haha"); }

async fn hahaha() { println!("hahaha"); }

fn main() { let mut v: Vec<Pin<Box<dyn Future<Output = ()>>>> = vec![]; v.push(Box::pin(haha())); v.push(Box::pin(hahaha())); task::block_on(async { for func in v { func.await } }) }

1 共 6 条评论, 1 页