Thomas Braun
Thomas Braun

Reputation: 535

Universal impl for all T, &T, &mut T, [T], &[T], *mut T

Consider this code:

pub trait Hello {
    fn hello(&self);
}

impl Hello for Any {
    fn hello(&self) {
        println!("Hello!!!!!");
    }
}

I remember seeing somewhere that there was a new feature in Rust that lets you implement a function that is directly accessible for all objects like this:

let foo = 0 as u8;
foo.hello();

Unfortunately, I have not been able to find it. Is there actually a global/universal "implementor"?

Upvotes: 0

Views: 267

Answers (1)

harmic
harmic

Reputation: 30587

Well, you could make a generic implementation of your trait:

pub trait Hello {
    fn hello(&self);
}

impl<T> Hello for T {
    fn hello(&self) {
        println!("Hello!!!!!");
    }
}

fn main() {
    let foo = 0 as u8;
    foo.hello();
    let bar = "world!".to_string();
    bar.hello();
}

Note that Rust currently does not allow specialization of generics (although there is an open RFC on it) so your trait implementation has to work as-is for any T.

Upvotes: 2

Related Questions