鉴于以下项目:
trait Trait { ... }
struct Thing { ... }
impl Trait for &Thing { ... }
是否可以编写一个返回 Thing
的函数,但这样:
- 具体类型
Thing
对消费者是隐藏的。 - 使用者只能访问
Trait
的方法和关联类型。
换句话说,我几乎想返回一个 impl Trait
,但这行不通,因为 Thing
没有实现 Trait
,只有 &Thing
可以。
// error: the trait bound `Thing: Trait` is not satisfied
fn get_thing() -> impl Trait {
Thing { ... }
}
(Trait 实际上位于另一个 crate 中,因此我无法添加全面的实现。)
最佳答案
不幸的是,当前没有语法可以传达“我正在返回一些匿名类型,其中对该类型的引用实现了某些特征”。但是,您可以引入自己的特征来尝试传达这个想法:
trait RefTrait {
type T<'a>: Trait where Self: 'a;
fn as_trait(&self) -> Self::T<'_>;
}
impl<T> RefTrait for T where for<'a> &'a T: Trait {
type T<'a> = &'a T where T: 'a;
fn as_trait(&self) -> Self::T<'_> {
&self
}
}
fn get_thing() -> impl RefTrait {
Thing
}
关于rust - 如何返回 impl Trait,其中类型的引用实现了该特征?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75568589/