gpt4 book ai didi

rust - 实现嵌套特征

转载 作者:行者123 更新时间:2023-11-29 07:43:53 24 4
gpt4 key购买 nike

我有一些特征(在删除函数和一些参数膨胀之后)看起来像:

trait Foo { }
trait Boo { }
trait Bar<T: Foo> { }
trait Baz { }

如果U工具 Bar<T>对于一些 T实现 Foo U工具 Boo , 然后可以推导出 Baz 的实现对于 U .但是,我无法为此编写有效的 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]

可以/如何在(稳定的)Rust 中做到这一点(希望没有任何动态调度)?

编辑:一些人暗示了一些类似的问题,这些问题基本上有两种方法(我发现它们都不适合我的情况):

  1. 使用关联类型。我不想这样做,因为我想跟踪 T ,例如我想编写一些具有类似 fn bla<T: Foo, U: Bar<T>, V: Bar<T>>() 签名的函数我想知道 UV实现 Bar<T>对于相同 T . (或者有关联类型的方法吗?)
  2. 通过放置 U 使用某种包装和 T在一个结构中。我也不想使用它,因为我有多个级别的这种“特征依赖性”,因此在每个级别中包装东西会使代码膨胀很多。

所以更新后的问题是:是否有不使用关联类型或包装器的解决方案?

最佳答案

你可以做到 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>>() { }

关于rust - 实现嵌套特征,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38459139/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com