rust 中奇怪的冲突实现

问题描述 投票:0回答:0

我正在用 Rust 制作一个小型 GUI 库以供练习。我的问题的最小可重现示例如下:


/// Trait for rendering engines
pub trait Renderer { /* ... */ }

pub trait Element<Win: Renderer> {
    fn paint(&self);
    fn width(&self) -> u32;
    fn height(&self) -> u32;
}

/// "Composed" element is element, that consists of multiple sub-elements, eg. button consists of frame and laconveniences a covinience trait, because implementing `Element` directly might be cumbersome.
pub trait ElComposed<Win: Renderer> {
    /// Returns the top-level subelement of self
    fn main_el(&self) -> Box<dyn Element<Win>>;
}

impl<T: ElComposed<Win>, Win: Renderer> Element<Win> for T {
    fn paint(&self) { self.main_el().paint() }
    fn width(&self) -> u32 { self.main_el().width() }
    fn height(&self) -> u32 { self.main_el().height() }
}

/// Element displaying just a circle
pub struct Circle;

/// Implementing `Element` trait directly on `Circle`
impl<Win: Renderer> Element<Win> for Circle {
    fn paint(&self) { todo!() }
    fn width(&self) -> u32 { todo!() }
    fn height(&self) -> u32 { todo!() }
}

操场链接

因为 Element trait 包含的方法比较多,直接实现可能会比较费时间,所以在代码中可以看到,我添加了 ElComposed convenience trait 使得由多个子元素组成的元素更容易实现(例如,按钮由框架和标签组成)。

但是现在,当我直接实现 Element 特性时(在上面的代码中),代码无法编译:

impl<Win: Renderer> Element<Win> for Circle

但是下游板条箱不能实现特性error[E0119]: conflicting implementations of trait `Element<_>` for type `Circle` | 21 | impl<T: ElComposed<Win>, Win: Renderer> Element<Win> for T { | ---------------------------------------------------------- first implementation here ... 31 | impl<Win: Renderer> Element<Win> for Circle { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ conflicting implementation for `Circle` | = note: downstream crates may implement trait `ElComposed<_>` for type `Circle` ElComposed,因为这两个特性都在我的板条箱中。那么为什么会出现这个错误,我该如何解决呢?

rust traits
© www.soinside.com 2019 - 2024. All rights reserved.