简体   繁体   English

具有盒装 impl 特征的结构

[英]Struct with boxed impl trait

I cannot figure out why this will not compile.我无法弄清楚为什么这不会编译。 I just want to have a struct with an iterator where the iterator is created with a function that returns impl Trait .我只想拥有一个带有迭代器的结构,其中迭代器是使用返回impl Trait的 function 创建的。 I changed my code to a minimal example for this post.我将我的代码更改为这篇文章的最小示例。

Open in Rust Playground 在 Rust 游乐场打开

struct Foo {
    pub it: Option<Box<dyn Iterator<Item=i32>>>,
}

impl Foo {
    fn new() -> Self {
        let it = Some(Box::new(my_numbers()));
        Self { it: it }
    }
}

fn my_numbers() -> impl Iterator<Item=i32> {
    1..10
}

Compiler output:编译器 output:

   |
8  |         Self { it: it }
   |                    ^^ expected trait object `dyn std::iter::Iterator`, found opaque type
...
12 | fn my_numbers() -> impl Iterator<Item=i32> {
   |                    ----------------------- the found opaque type
   |
   = note: expected enum `std::option::Option<std::boxed::Box<(dyn std::iter::Iterator<Item = i32> + 'static)>>`
              found enum `std::option::Option<std::boxed::Box<impl std::iter::Iterator>>`

Edit:编辑:

I found one workaround is using #![feature(type_alias_impl_trait)] , but this is not stable.我发现一种解决方法是使用#![feature(type_alias_impl_trait)] ,但这并不稳定。

Casting the boxed value, ie Box::new(my_numbers()) as Box<dyn Iterator<Item=_>> solves this with stable Rust 1.41.0.将装箱值,即Box::new(my_numbers()) as Box<dyn Iterator<Item=_>>通过稳定的 Rust 1.41.0 解决了这个问题。 It's possible that enabling type_alias_impl_trait helps with this missing type inference aspect.启用type_alias_impl_trait可能有助于解决这个缺失的类型推断方面。

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

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