Rust中特征的相互矛盾的实现 [英] Conflicting implementations of trait in Rust

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

问题描述

我想为&'一个str 和整数最多 i32 实现一个自定义特征,但Rust不允许我:

 使用std :: convert :: Into; 

酒吧特质UiId {
fn push(& self);
}

impl<'a>用于&'a str {
fn push(& self){}
}

impl< T的UiId:到< i32>>用于T {
fn push(& self){}
}

fn main(){}

无法编译时出现以下错误:

 错误[E0119]:'& str`类型的特征'UiId'的冲突实现:
- > src / main.rs:11:1
|
7 | IMPL<一> UiId for&'a str {
| -------------------------首先在这里执行
...
11 | impl< T:进入< i32>用于T {
|的UiId ^ `^^^^^^^^^^^^^^^^^^^^^^^^^^^`& str`的​​相互冲突
|
= note:在未来的版本中,上游箱子可以为`i32`类型添加新的特性`std :: convert :: From<& str>`
pre>

&'a str 不会执行进入< i32> 。是否可以为&'a str 实现 UiId ,并且所有可以转换为 i32 没有指定具体的类型?

c>不会执行进入< i32> 不会被考虑在内,因为不能保证它以后不能添加。这会破坏你的代码。



所以如果允许这种情况发生,可能会导致将实现添加到库特征中变得更加困难。



不幸的是,我找不到这方面的文档,无论是在 Rust编程语言书籍也不在参考手册中。



我能找到的最好是 RFC 1023 ,其中说 crate不能依赖类型:!Trait 除非类型 Trait 是本地的。


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

This fails to compile with the following error:

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 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?

解决方案

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.

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

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中特征的相互矛盾的实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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