Implementing trait for &[u8]

Hello,
I'm implementing a trait for &[u8] but I can not use self in the trait implementation.

pub trait Xor {
    fn xor(&self, key_bytes: &[u8]) -> &[u8] {
        dbg!(self);
        unimplemented!()
    }
}

impl Xor for [u8] {}

let xa = b"1234";
xa.xor(b"123");

Unfortunately, It can't use self in trait as a u8.

error[E0277]: `Self` doesn't implement `std::fmt::Debug`
 --> src/main.rs:8:9
  |
7 |     fn xor(&self, key_bytes: &[u8]) -> &[u8] {
  |                                             - help: consider further restricting `Self`: `where Self: std::fmt::Debug`
8 |         dbg!(self);
  |         ^^^^^^^^^^^ `Self` cannot be formatted using `{:?}` because it doesn't implement `std::fmt::Debug`
  |
  = help: the trait `std::fmt::Debug` is not implemented for `Self`
  = note: required because of the requirements on the impl of `std::fmt::Debug` for `&Self`
  = note: required because of the requirements on the impl of `std::fmt::Debug` for `&&Self`
  = note: required by `std::fmt::Debug::fmt`
  = note: this error originates in a macro outside of the current crate (in Nightly builds, run with -Z external-macro-backtrace for more info)

You have no where clause that says that self can be debug-printed in the trait, so you can't use dbg! there. If you add it, it should work:

pub trait Xor: Debug {
    fn xor(&self, key_bytes: &[u8]) -> &[u8] {
        dbg!(self);
        unimplemented!()
    }
}

impl Xor for [u8] {}

fn main() {
    let xa = b"1234";
    xa.xor(b"123");
}

playground

1 Like

It can't format self because it doesn't know if Self implements std::fmt::Debug.
If you do this it works and will require that everything that implements Xor also implements Debug:

pub trait Xor: Debug {
...
}

Edit: And alice was 10seconds faster...

1 Like

You should move the function implementation to the impl block. Otherwise you are trying to create a default implementation for any type that implements Xor, not just [u8]

pub trait Xor {
    fn xor(&self, key_bytes: &[u8]) -> &[u8];
}

impl Xor for [u8] {
    fn xor(&self, key_bytes: &[u8]) -> &[u8] {
        dbg!(self);
        unimplemented!()
    }
}

let xa = b"1234";
xa.xor(b"123");
2 Likes

This question was asked on StackOverflow at the same time, where trentcl took the time to write a proper answer.

Please let people know when you ask the same question at several places.

3 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.