Rust特质别名

3

我正在开发一个演员项目,需要使用trait别名,因为原始名称太长了,但即使使用夜版功能#![feature(trait_alias)]似乎也无法实现。

简而言之,我写了一个playground: 我想让别名A<T>更短,因为我在实际情况下有许多泛型类型在A中;同时我想从其实现B中访问type Output = Self;。 感谢任何帮助。

https://play.rust-lang.org/?version=nightly&mode=debug&edition=2018&gist=5a9bb8d3f76112c0b73ea1da8af34959

#![feature(trait_alias)]

trait A<T> {
    type Output;
    fn test(a: T) -> Self::Output;
}

//To alias the trait, real situation longer than this.
//attempt 1:
trait B: A<String>{}

//attempt 2:
//trait B : A<String, Output=Self> where Self: std::marker::Sized {}
//impl<T> B for T where T: A<String, Output=T> {}

//attempt 3 with trait_alias:
//trait B = A<String>;

struct SA;

impl B for SA {
    type Output = Self;
}


《不稳定特性手册》建议 impl TraitAlias for Type 不支持该语法: "trait_alias 特性添加了 trait 别名的支持。这允许为一个或多个 trait(目前仅限于单个常规 trait 和任意数量的自动 trait)创建别名,并在标准 trait 作为约束条件或 trait 对象使用的地方引用它们 [强调部分已添加]." - Mac O'Brien
@CormacO'Brien 哈哈,你在我的答案后1秒钟发布了这个 xd。 - Stargateur
请在这里演示“实际情况”,因为目前我只看到一个通用的。你说“我的问题是我有太多的通用”,但至少在你的[mcve]中展示多于1个。 - Stargateur
1个回答

4

trait alias 只意味着可以用在 traits 通常被用作约束或 trait 对象的地方。来源

因此,如果你的使用情况不符合,你就无法这样做。


谢谢,是的,#![feature(trait_alias)] 看起来是这样的,不知道有没有其他的方法可以实现。 - raul
@raul 如果你不知道为什么想要做你想做的事情,那就不行。 - Stargateur
1
不,这是不可能的。 impl块既不是特质限定也不是特质对象 - 这两者都与函数参数有关。 - Tim McNamara

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接