Default implementation of a trait for byte vectors

47 Views Asked by At

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.

1

There are 1 best solutions below

0
harmic On BEST ANSWER

You can't provide a default implementation within the trait itself - a default implementation must work for any type that implements the trait.

The underlying problem is that in do_smth I need the object to be converted to a byte slice.

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).

pub trait MKF {
    fn get_appendix(&self) -> String { "Hey".to_string() }
    fn is_live(&self) -> bool { true }
    fn is_valid(&self) -> bool { false }
    fn do_smth(&self) -> usize;
}


impl<T: AsRef<[u8]>> MKF for T {
    fn do_smth(&self) -> usize {
        let x = self.as_ref();
        x.len()
    }
}

pub fn main() {

    let s = "Hello World".to_string();

    println!("{}", s.do_smth());

}

Playground