我正在尝试实现一个具有一堆字段的泛型结构,其中每个字段类型都应该知道整个结构的确切类型。这是一种策略模式。
pub struct Example<S: Strategy<Example<S, D>>, D> {
pub s: S,
pub a: S::Associated,
pub data: D,
}
pub trait Strategy<T> {
type Associated;
fn run(&self, &T);
}
pub trait HasData {
type Data;
fn data(&self) -> &Self::Data;
}
impl<S: Strategy<Self>, D> Example<S, D> {
// ^^^^
// the complex code in this impl is the actual meat of the library:
pub fn do_it(&self) {
self.s.run(self); // using the Strategy trait
}
}
impl<S: Strategy<Self>, D> HasData for Example<S, D> {
type Data = D;
fn data(&self) -> &D {
&self.data
}
}
然后我打算从上面的“库”中实例化泛型:
pub struct ExampleStrat;
pub struct ExampleData;
impl<E: HasData<Data = ExampleData>> Strategy<E> for ExampleStrat {
type Associated = ();
fn run(&self, e: &E) {
let _ = e.data();
// uses ExampleData here
}
}
let example = Example {
s: ExampleStrat,
a: (),
data: ExampleData,
};
example.do_it();
在我的实际代码中,我有很多不同的“策略”和多个数据字段,所以Example
类型有一个令人印象深刻的泛型列表,如果库用户不需要明确说明它们(或者至少不经常),而只需要使用HasData
特征(及其相关类型,而不是泛型类型参数),我会很高兴。
如果struct Example<S, D>
中没有类型绑定,这实际上(令人惊讶地)会工作得很好,比我最初预期的(在fighting with Self
in the struct
bounds之后)要好得多。然而,当结构应该只与受约束的类型一起使用时,建议使用duplicate the impl
trait bounds on the struct
,在我的例子中,我实际上需要它们能够将Associated
类型用于a
字段。
现在编译器正在抱怨
error[E0275]: overflow evaluating the requirement `main::ExampleStrat: Strategy<Example<main::ExampleStrat, main::ExampleData>>`
--> src/main.rs:42:9
|
42 | a: (),
| ^^^^^
|
= note: required because of the requirements on the impl of `HasData` for `Example<main::ExampleStrat, main::ExampleData>`
= note: required because of the requirements on the impl of `Strategy<Example<main::ExampleStrat, main::ExampleData>>` for `main::ExampleStrat`
我怎么才能解决这个问题呢?我是不是在尝试做一些不可能的事情,我是不是做错了,或者这应该是可能的,但我却成了a compiler bug的牺牲品?我的整个设计有缺陷吗?
https://stackoverflow.com/questions/50657585
复制相似问题