We can define a trait and its implementation for byte vectors:
pub trait MKF {
fn do_smth(&self) -> String;
}
impl MKF for Vec<u8> {
fn do_smth(&self) -> String {
String::from("hello")
}
}
I want to provide a default implementation which works for vectors in the trait declaration itself. Because there are other blanket implementations in the trait which are there, I am hoping I can just group them all there. Is this possible?
I tried for example
pub trait MKF<V: Vec<u8>> {
fn get_appendix(&self) -> String {...}
fn is_live(&self) -> bool {...}
fn is_valid(&self) -> bool {...}
fn do_smth(&self) -> String {
String::from("hello")
}
}
which does not work, as Vec is a struct and not a trait. Same happens trying to apply on the fn:
pub trait MKF {
fn do_smth<V: Vec<u8>>(&self) {...}
}
Is there a way to do this? The underlying problem is that in do_smth I need the object to be converted to a byte slice. Therefore only objects which can be converted to byte slices should be using this trait.
You can't provide a default implementation within the trait itself - a default implementation must work for any type that implements the trait.
You can make a blanket implementation that works for any type which implements a trait, for example
AsRef<[u8]>. That blanket implementation would have to implement all the functions in the trait (other than those with actual default implementations).Playground