首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >奇怪地重复出现的通用特征模式:溢出评估需求

奇怪地重复出现的通用特征模式:溢出评估需求
EN

Stack Overflow用户
提问于 2018-06-02 21:49:52
回答 2查看 358关注 0票数 0

我正在尝试实现一个具有一堆字段的泛型结构,其中每个字段类型都应该知道整个结构的确切类型。这是一种策略模式。

代码语言:javascript
复制
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
    }
}

然后我打算从上面的“库”中实例化泛型:

代码语言:javascript
复制
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字段。

现在编译器正在抱怨

代码语言:javascript
复制
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的牺牲品?我的整个设计有缺陷吗?

EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50657585

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档