How to call the method of a type for which the trait is implemented?

Hello.

Consider the following code:

trait MyTrait {
    fn len(&self) -> usize;
}

impl MyTrait for &'static [u8] {
    fn len(&self) -> usize {
        self.len()
    }
}

static ARR: &'static [u8] = &[1, 2, 3];

fn main() {
    let mytrait: &dyn MyTrait = &ARR;
    mytrait.len();
    println!("End");
}

Here, the compiler tells me that the len method of MyTrait recursively calls itself, and when I run the program that is exactly what happens (stack overflow).
How do I tell the compiler I want to call the method of the parent/super type for which the trait is implemented, in that case, the method len of &'static [u8] ?

Thanks!

impl MyTrait for &'static [u8] {
    fn len(&self) -> usize {
        <[u8]>::len(self)
    }
}

See also: Advanced Traits - The Rust Programming Language

1 Like

Use fully qualified syntax: <[u8]>::len(self)

1 Like

Rust automatically favors an inherent method over a trait method of the same name, if one exists.

In this case, your self type is & &'static [u8] which does not have a len method, even though one is found via deref coercion. The fix is simple:

(*self).len()
6 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.