[英]How do you implement a trait for T where T: Foo OR Bar
In rust, you can automatically implement a trait for any type that implements some other combination of traits.在 rust 中,您可以为任何实现了其他一些特征组合的类型自动实现特征。 Ie:
IE:
impl<T: Foo + Bar> SomeTrait for T {
some_function(&self) {
/*...*/
}
}
What I'm trying to do is define a relationship where Foo
and Bar
are both enough to implement SomeTrait
by themselves.我要做的是定义一种关系,其中
Foo
和Bar
都足以自己实现SomeTrait
。 Basically, something like this:基本上,是这样的:
impl<T: Foo> SomeTrait for T {
some_function(&self) {
/*...*/
}
}
impl<T: Bar> SomeTrait for T {
some_function(&self) {
/*...*/
}
}
This won't compile, because you're implementing SomeTrait
for T
twice and the compiler can't possibly know what to do in the case where T: Foo + Bar
, but it'd be really nice to be able to do this.这不会编译,因为您为
T
实现SomeTrait
两次,编译器不可能知道在T: Foo + Bar
的情况下要做什么,但能够做到这一点真的很好。
Is there some way to "abstract" around this problem so that I can call some_function()
on a T
that implements Foo
OR Bar
?有没有办法“抽象”解决这个问题,以便我可以在实现
Foo
OR Bar
的T
上调用some_function()
? Or am I stuck with having to pick only one implementation?还是我坚持只选择一种实现?
If you use nightly, you can use the marker_trait_attr
feature.如果您每晚使用,则可以使用
marker_trait_attr
功能。 It allows you to have overlapping impls for a trait that has the attribute #[marker]
.它允许您对具有属性
#[marker]
的特征具有重叠的实现。 Note that the trait should have no associated items - it must be empty.请注意,特征应该没有关联的项目 - 它必须是空的。
Thus, you can define a marker trait FooOrBar
(I made it in a private module so it's sealed and people cannot implement it manually):因此,您可以定义一个标记特征
FooOrBar
(我在一个私有模块中制作它,因此它是密封的,人们无法手动实现它):
#![feature(marker_trait_attr)]
mod private {
#[marker]
pub trait FooOrBar {}
impl<T: super::Foo> FooOrBar for T {}
impl<T: super::Bar> FooOrBar for T {}
}
And then implement the trait SomeTrait
for any type that implements FooOrBar
:然后为实现
SomeTrait
的任何类型实现特征FooOrBar
:
impl<T: private::FooOrBar> SomeTrait for T {
fn foo(&self) { /* ... */ }
}
Playground . 游乐场。
For stable, unfortunately, I don't think there is a way but a redesign.不幸的是,对于稳定版,我认为除了重新设计之外别无他法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.