Rust 中特征的实现冲突

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

我想为

&'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>
。是否可以在不指定具体类型的情况下为
UiId
以及所有可以转换为
&'a str
的内容实现
i32
?我怎样才能做到这一点?

generics rust traits
3个回答
22
投票

不考虑

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

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

不幸的是,我在《The Rust 编程语言》一书中和《参考手册》中都找不到相关文档。 我能找到的最好的是RFC 1023,它说

一个板条箱[...]不能依赖

Type: !Trait持有,除非Type

Trait
是本地的。

    

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


14
投票
Numeric

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

Numeric

特征必须是

pub

,因为他们警告未来版本将不允许在公共界面中使用私有特征。


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) {}
}

    

这有点恶心,但您可以解决与类型参数中标记结构的冲突,如下所示:

0
投票

输出:

UiId for Into<i32>
UiId for str

缺点是,据我所知,您在任何地方使用该特征作为类型参数 边界,您还必须为标记添加类型参数:

fn push_uiid<Marker, U: UiId<Marker>>(u: U) {
    u.push();
}

https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=c98d6a461e8535d2a23045b510917cc8

    

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.