[英]How can I implement the From trait for all types implementing a trait but use a specific implementation for certain types?
I am implementing the std::convert::From
trait for a struct containing a Cow<str>
. 我正在为包含
Cow<str>
的结构实现std::convert::From
特征。 Is there a way to use the same implementation for all different kinds of integers ( u8
, u16
, u32
, usize
and so on)? 有没有办法使用了各种不同类型相同的整数执行(的方式
u8
, u16
, u32
, usize
等)?
use std::borrow::Cow;
pub struct Luhn<'a> {
code: Cow<'a, str>,
}
I can easily implement code for all integers using a trait bound on the ToString
trait, but then I cannot use a specific implementation for str
and String
- this way the benefits of Cow
cannot be exploited. 我可以使用绑定在
ToString
特征上的特征来轻松地为所有整数实现代码,但是随后我无法对str
和String
使用特定的实现-这样就无法利用Cow
的好处。 When I write specific implementations for str
and String
, I get a compile error: 当我为
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<'_>`
I understand that this is due to the fact that Rust does not offer function overloading. 我知道这是由于Rust不提供函数重载这一事实。 How could this be solved in an elegant way?
如何以一种优雅的方式解决这个问题?
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()),
}
}
}
Since &str
and String
both implement ToString
, you can use the unstable specialization feature: 由于
&str
和String
都实现ToString
,因此可以使用不稳定的专业化功能:
#![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),
}
}
}
That being said, you cannot implement Display
for Luhn
because you'd run into How is there a conflicting implementation of `From` when using a generic type? 话虽如此,您不能实现
Display
for Luhn
因为您在使用泛型类型时会遇到“ From”的冲突实现吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.