我正在为包含std::convert::From
的结构实现Cow<str>
特性。有没有办法对所有不同类型的整数使用相同的实现(u8
,u16
,u32
,usize
等)?
use std::borrow::Cow;
pub struct Luhn<'a> {
code: Cow<'a, str>,
}
我可以使用ToString
特征上绑定的特征轻松实现所有整数的代码,但是我不能使用str
和String
的特定实现 - 这样就无法利用Cow
的好处。当我为str
和String
编写特定的实现时,我得到一个编译错误:
error[E0119]: conflicting implementations of trait `std::convert::From<&str>` for type `Luhn<'_>`: --> src/lib.rs:23:1 | 7 | impl<'a> From<&'a str> for Luhn<'a> { | ----------------------------------- first implementation here ... 23 | impl<'a, T: ToString> From<T> for Luhn<'a> { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ conflicting implementation for `Luhn<'_>`
我知道这是因为Rust不提供函数重载。怎么能以优雅的方式解决这个问题?
impl<'a> From<&'a str> for Luhn<'a> {
fn from(input: &'a str) -> Self {
Luhn {
code: Cow::Borrowed(input),
}
}
}
impl<'a> From<String> for Luhn<'a> {
fn from(input: String) -> Self {
Luhn {
code: Cow::Owned(input),
}
}
}
impl<'a, T: ToString> From<T> for Luhn<'a> {
fn from(input: T) -> Self {
Luhn {
code: Cow::Owned(input.to_string()),
}
}
}
由于&str
和String
都实现了ToString
,你可以使用不稳定的specialization功能:
#![feature(specialization)]
use std::borrow::Cow;
pub struct Luhn<'a> {
code: Cow<'a, str>,
}
impl<'a, T: ToString> From<T> for Luhn<'a> {
default fn from(input: T) -> Self {
// ^^^^^^^
Luhn {
code: Cow::Owned(input.to_string()),
}
}
}
impl<'a> From<&'a str> for Luhn<'a> {
fn from(input: &'a str) -> Self {
Luhn {
code: Cow::Borrowed(input),
}
}
}
impl<'a> From<String> for Luhn<'a> {
fn from(input: String) -> Self {
Luhn {
code: Cow::Owned(input),
}
}
}
话虽这么说,你不能为Display
实施Luhn
,因为你遇到了How is there a conflicting implementation of `From` when using a generic type?