“一揽子实现”在 Rust 中返回错误

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

我创造了一个特质:

pub trait DimenBasics {
    // --snip--
    fn get_value(&self) -> f64;

    fn get_unit(&self) -> String;

    fn verified_add(&self, other: &Self) -> Result<Self, String>
    where
        Self: Sized;
    // --snip--
}

我试图做一个“一揽子实施”,这是代码:

impl<D: DimenBasics> UpperExp for D {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        write!(f, "{:E}{}", self.get_value(), self.get_unit())
    }
}

我认为这很好,因为对我来说,它类似于 rust 文档中的示例:

impl<T: Display> ToString for T {
    // --snip--
}

但是我收到了这个错误:

error[E0210]: type parameter `D` must be used as the type parameter for some local type (e.g., `MyStruct<D>`)
    --> dimension/src/lib.rs:1111:6
     |
1111 | impl<D: DimenBasics> UpperExp for D
     |      ^ type parameter `D` must be used as the type parameter for some local type
     |
     = note: implementing a foreign trait is only possible if at least one of the types for which it is implemented is local
     = note: only traits defined in the current crate can be implemented for a type parameter

导致此错误的原因是什么?

rust traits
1个回答
0
投票

编译器的错误消息看起来很清楚。您不能为您自己的板条箱中未定义的特征创建一揽子实现。您从标准库中给出的示例有效,因为

ToString
和毯子实现都在同一个箱子中。

这是不允许的,因为否则两个板条箱可能会创建这样一个全面的实现,然后它们就会发生冲突。这会造成您无法同时使用两个板条箱的情况,因为它们都决定创建相同外部特征的全面实现。随着更多的板条箱被上传并且依赖图变得足够复杂,发生这种情况的可能性急剧增加,这将是一种难以维持的情况。

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