简体   繁体   English

有没有办法将匿名类型引用为结构成员?

[英]Is there a way to reference an anonymous type as a struct member?

Consider the following Rust code:考虑以下 Rust 代码:

use std::future::Future;
use std::pin::Pin;

fn main() {
    let mut v: Vec<_> = Vec::new();
    for _ in 1..10 {
        v.push(wrap_future(Box::pin(async {})));
    }
}

fn wrap_future<T>(a: Pin<Box<dyn Future<Output=T>>>) -> impl Future<Output=T> {
    async {
        println!("doing stuff before awaiting");
        let result=a.await;
        println!("doing stuff after awaiting");
        result
    }
}

As you can see, the futures I'm putting into the Vec don't need to be boxed, since they are all the same type and the compiler can infer what that type is.如您所见,我放入Vec中的 futures 不需要装箱,因为它们都是相同的类型并且编译器可以推断出该类型是什么。

I would like to create a struct that has this Vec<...> type as one of its members, so that I could add a line at the end of main() :我想创建一个将此Vec<...>类型作为其成员之一的struct ,以便我可以在main()的末尾添加一行:

let thing = MyStruct {myvec: v};

without any additional overhead (ie boxing).没有任何额外的开销(即装箱)。

Type inference and impl Trait syntax aren't allowed on struct members, and since the future type returned by an async block exists entirely within the compiler and is exclusive to that exact async block, there's no way to reference it by name.结构成员不允许类型推断和impl Trait语法,并且由于异步块返回的未来类型完全存在于编译器中并且是那个确切的异步块独有的,因此无法通过名称引用它。 It seems to me that what I want to do is impossible.在我看来,我想做的事是不可能的。 Is it?是吗? If so, will it become possible in a future version of Rust?如果是这样,它会在 Rust 的未来版本中成为可能吗?

I am aware that it would be easy to sidestep this problem by simply boxing all the futures in the Vec as I did the argument to wrap_future() but I'd prefer not to do this if I can avoid it.我知道,就像我对wrap_future()的论证一样,只需将Vec中的所有 futures 装箱就可以很容易地回避这个问题,但如果可以避免的话,我宁愿不这样做。

I am well aware that doing this would mean that there could be only one async block in my entire codebase whose result values could possibly be added to such a Vec , and thus that there could be only one function in my entire codebase that could create values that could possibly be pushed to it.我很清楚这样做意味着我的整个代码库中只能有一个async块,其结果值可能被添加到这样的Vec中,因此我的整个代码库中只能有一个 function 可以创建值可以推给它。 I am okay with this limitation.我可以接受这个限制。

Nevermind, I'm stupid.没关系,我很笨。 I forgot that structs could have type parameters.我忘记了结构可以有类型参数。

struct MyStruct<F> where F: Future<Output=()> {
     myvec: Vec<F>,
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM