繁体   English   中英

当其中一个相关类型无法命名时,如何实现特征?

[英]How to implement a trait when one of the associated types is impossible to name?

我有一个返回impl Trait的函数,所以我没有访问具体的返回类型。 我需要使用该函数的返回值作为特征中的关联类型。 我怎么做?

这是一个简化的例子:

fn f() -> impl Iterator<Item = u8> {
    std::iter::empty()
}

struct S;

impl IntoIterator for S {
    type Item = u8;
    type IntoIter = (); // What can I write here ?

    fn into_iter(self) -> Self::IntoIter {
        f()
    }
}

它甚至可以做(没有诉诸拳击迭代器)?

不幸的是,你做不到。 至少还没有。

有一个RFC, 命名存在和impl Trait变量声明跟踪问题 ),它允许您在模块级别声明一个公共类型名称 ,其类型定义是从它在模块中使用的方式推断出来的。 模块的用户可以通过其公共名称引用此类型,并且可以将其用作关联类型。

很难猜测新功能何时会稳定下来,同时确实没有太多好的选择。 除了因用例的具体情况而可能起作用的事情之外,一般的解决方法是使用特征对象:

impl IntoIterator for S {
    type Item = u8;
    type IntoIter = Box<dyn Iterator<Item = u8>>;

    fn into_iter(self) -> Self::IntoIter {
        Box::new(f())
    }
}

如果可以使用夜间功能,您可以在稳定之前帮助测试RFC:

#![feature(existential_type)]

impl IntoIterator for S {
    type Item = u8;
    existential type IntoIter: Iterator<Item = u8>;

    fn into_iter(self) -> Self::IntoIter {
        f()
    }
}

暂无
暂无

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

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