【发布时间】:2018-11-12 10:21:31
【问题描述】:
我正在尝试用一堆字段实现一个通用结构,其中每个字段类型都应该知道整个结构的确切类型。这是一种策略模式。
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 类型用于@ 987654336@字段。
现在编译器在抱怨
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 的牺牲品?我的完整设计有缺陷吗?
【问题讨论】:
-
一般来说,将特征边界放在结构或特征的类型参数上并不是一个好习惯。如果您将它们移至 impl,那么您将更清楚地看到为什么会发生循环依赖。
-
@PeterHall 我确实看到了循环依赖,但我不明白为什么它无法解决。
-
@PeterHall this (without using the associated type) 不做同样的事情吗?
-
是的。但是您在主结构中丢失了泛型类型。大概您不想将其硬编码为
()?
标签: compiler-errors rust traits type-constraints