实现嵌套特征
Implementing Nested Traits
我有一些特征(在删除函数和一些参数膨胀之后)看起来像:
trait Foo { }
trait Boo { }
trait Bar<T: Foo> { }
trait Baz { }
如果 U
为一些 T
实施 Foo
和 U
实施 [=18] Bar<T>
=],那么就可以为 U
推导出 Baz
的实现。但是,我无法为此编写有效的 Rust 代码。
一些尝试是:
impl<T: Foo, U: Bar<T> + Boo> Baz for U { }
这给出了
error: the type parameter T
is not constrained by the impl trait, self type, or predicates [E0207]
而
impl<U: Bar<T> + Boo> Baz for U { }
产量
error: type name T
is undefined or not in scope [E0412]
one/how 可以在(稳定的)Rust 中做到这一点吗(希望没有任何动态调度)?
编辑:有些人暗示了一些类似的问题,基本上有两种方法(我发现它们都不适合我的情况):
- 使用关联类型。我不想这样做,因为我想跟踪
T
,例如我想编写一些具有 fn bla<T: Foo, U: Bar<T>, V: Bar<T>>()
签名的函数,我想知道 U
和 V
为 same[=58 实现 Bar<T>
=] T
。 (或者有关联类型的方法吗?)
- 通过将
U
和 T
放入结构中来使用某种包装。我也不想使用它,因为我有多个这样的级别 "trait dependencies",所以在每个级别中包装东西会使代码膨胀很多。
所以更新后的问题是:是否有不使用关联类型或包装器的解决方案?
您可以将 T
设为关联类型:
trait Foo { }
trait Boo { }
trait Bar {
type T: Foo;
}
trait Baz { }
impl<U: Bar + Boo> Baz for U
// this where clause is not necessary (this bound is already true)
// where U::T: Foo
{ }
I don't want to do this because I want to keep track of T
, e.g. I want to write some functions which have a signature like fn bla<T: Foo, U: Bar<T>, V: Bar<T>>()
where I want to know that U
and V
implement Bar<T>
for the same T
. (Or is there way of doing this with associated types?)
是的,您可以使用关联类型来做到这一点:
fn bla<U: Bar, V: Bar<T = U::T>>() { }
我有一些特征(在删除函数和一些参数膨胀之后)看起来像:
trait Foo { }
trait Boo { }
trait Bar<T: Foo> { }
trait Baz { }
如果 U
为一些 T
实施 Foo
和 U
实施 [=18] Bar<T>
=],那么就可以为 U
推导出 Baz
的实现。但是,我无法为此编写有效的 Rust 代码。
一些尝试是:
impl<T: Foo, U: Bar<T> + Boo> Baz for U { }
这给出了
error: the type parameter
T
is not constrained by the impl trait, self type, or predicates [E0207]
而
impl<U: Bar<T> + Boo> Baz for U { }
产量
error: type name
T
is undefined or not in scope [E0412]
one/how 可以在(稳定的)Rust 中做到这一点吗(希望没有任何动态调度)?
编辑:有些人暗示了一些类似的问题,基本上有两种方法(我发现它们都不适合我的情况):
- 使用关联类型。我不想这样做,因为我想跟踪
T
,例如我想编写一些具有fn bla<T: Foo, U: Bar<T>, V: Bar<T>>()
签名的函数,我想知道U
和V
为 same[=58 实现Bar<T>
=]T
。 (或者有关联类型的方法吗?) - 通过将
U
和T
放入结构中来使用某种包装。我也不想使用它,因为我有多个这样的级别 "trait dependencies",所以在每个级别中包装东西会使代码膨胀很多。
所以更新后的问题是:是否有不使用关联类型或包装器的解决方案?
您可以将 T
设为关联类型:
trait Foo { }
trait Boo { }
trait Bar {
type T: Foo;
}
trait Baz { }
impl<U: Bar + Boo> Baz for U
// this where clause is not necessary (this bound is already true)
// where U::T: Foo
{ }
I don't want to do this because I want to keep track of
T
, e.g. I want to write some functions which have a signature likefn bla<T: Foo, U: Bar<T>, V: Bar<T>>()
where I want to know thatU
andV
implementBar<T>
for the sameT
. (Or is there way of doing this with associated types?)
是的,您可以使用关联类型来做到这一点:
fn bla<U: Bar, V: Bar<T = U::T>>() { }