I have a trait, MyGoodTrait
, with the function label(&self) -> &str
. I want every implementor of MyGoodTrait
to also implement Display
and FromStr
. However, I do not necessarily need Display
and FromStr
to be supertraits of MyGoodTrait
. I would rather somehow have a default implementation of Display
and FromStr
, which will internally use the label
function from MyGoodTrait
. That way, every implementor of MyGoodTrait
will get Display
and FromStr
"for free", as if there was a default implementation for those traits.
这是一个与我想要执行的操作类似的示例,但是无法编译:
use std::str::FromStr;
pub trait MyGoodTrait {
fn new() -> Self;
fn label(&self) -> &'static str;
}
impl FromStr for dyn MyGoodTrait {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(Self::new())
}
}
pub struct A {}
impl MyGoodTrait for A {
fn new() -> Self {
A{}
}
fn label(&self) -> &'static str {
"A"
}
}
pub struct B {}
impl MyGoodTrait for B {
fn new() -> Self {
B{}
}
fn label(&self) -> &'static str {
"B"
}
}
// In this hypothetical, A and B now both have `fmt` and `from_str` functions
Is there a way to write this default implementation of Display
and FromStr
, such that I do not have to duplicate the code for each struct that implements MyGoodTrait
?
Note: My actual use case is that I have a trait which has serde::se::Serialize
and serde::de::Deserialize
as supertraits. The implementors of my trait will be used as keys in a map, and I will serialize the map to JSON, so I need the implementors to be serialized to Strings. So this may be an example of the XY Problem