我想为
&'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
?我怎样才能做到这一点?
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) {}
}
这有点恶心,但您可以解决与类型参数中标记结构的冲突,如下所示: