Rust 中 trait 的冲突实现 [英] Conflicting implementations of trait in Rust

查看:25
本文介绍了Rust 中 trait 的冲突实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to implement a custom trait for &'a str and for integer numbers up to i32, but Rust does not allow me to:

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.是否可以为 &'a str 和所有可以转换为 i32 的东西实现 UiId 而不指定具体类型?我该怎么做?

&'a str does not implement Into<i32>. Is it possible to implement UiId for &'a str and everything that can be converted into i32 without specifying concrete types? How can I do that?

推荐答案

&'a str 没有实现 Into 的事实没有考虑进去帐户,因为不能保证以后不能添加.这会破坏您的代码.

The fact that &'a str does not implement Into<i32> is not taken into account, because there is no guarantee that it couldn't be added later. This would then break your code.

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

So if this were allowed the possible breakage would make it harder to add implementations to library traits.

不幸的是,我在 The Rust Programming Language 一书中和参考手册.

Unfortunately I couldn't find documentation for that, neither in The Rust Programming Language Book nor in the Reference Manual.

我能找到的最好的是 RFC 1023,这表示一个板条箱 [...] 不能依赖 Type: !Trait 持有,除非 TypeTrait 是本地的.

The best I could find is RFC 1023, which says that a crate [...] cannot rely that Type: !Trait holds unless Type or Trait is local.

这篇关于Rust 中 trait 的冲突实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆