繁体   English   中英

Rust 中 trait 的冲突实现

[英]Conflicting implementations of trait in Rust

我想为&'a str和高达i32整数实现自定义特征,但 Rust 不允许我:

use std::convert::Into;

pub trait UiId {
    fn push(&self);
}

impl<'a> UiId for &'a str {
    fn push(&self) {}
}

impl<T: Into<i32>> UiId for T {
    fn push(&self) {}
}

fn main() {}

这无法编译并出现以下错误:

error[E0119]: conflicting implementations of trait `UiId` for type `&str`:
  --> src/main.rs:11:1
   |
7  | impl<'a> UiId for &'a str {
   | ------------------------- first implementation here
...
11 | impl<T: Into<i32>> UiId for T {
   | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ conflicting implementation for `&str`
   |
   = note: upstream crates may add new impl of trait `std::convert::From<&str>` for type `i32` in future versions

&'a str没有实现Into<i32> 是否可以为&'a str和所有可以在不指定具体类型的情况下转换为i32内容实现UiId 我该怎么做?

没有考虑&'a str没有实现Into<i32>的事实,因为不能保证以后不能添加它。 这会破坏你的代码。

因此,如果允许这样做,则可能的破坏将使向库特征添加实现变得更加困难。

不幸的是,我在The Rust Programming Language Book 和Reference Manual 中都找不到相关文档。

我能找到的最好的是RFC 1023 ,它说板条箱 [...] 不能依赖该Type: !Trait持有,除非TypeTrait是本地的。

我找到了一种使用标记特征的解决方法。 无需夜间或实验性功能。 诀窍是我在我的 crate 中定义了标记特征并且不导出它,因此上游 crate 不可能在我实现它的类以外的类上定义标记。

标记特征下方是Numeric

我使用它,以便我可以为任何可以转换为 f64 的东西实现 Into,也可以为单独的 impl 中的字符串和其他类型实现。

Numeric trait 必须是pub因为它们警告未来版本将禁止在公共接口中使用私有 Trait。


use std::convert::Into;

pub trait Numeric {}
impl Numeric for f64 {}
impl Numeric for f32 {}
impl Numeric for i64 {}
impl Numeric for i32 {}
impl Numeric for i16 {}
impl Numeric for i8 {}
impl Numeric for isize {}
impl Numeric for u64 {}
impl Numeric for u32 {}
impl Numeric for u16 {}
impl Numeric for u8 {}
impl Numeric for usize {}


pub trait UiId {
    fn push(&self);
}

impl<'a> UiId for &'a str {
    fn push(&self) {}
}

impl<T: Into<i32> + Numeric> UiId for T {
    fn push(&self) {}
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM