Generic struct impl blocks

Hi, while reading through some examples in the Rust book, I noticed that I can define impl blocks for specifically-typed structs; this is quite cool as I can define custom behavior for the same struct with different types: e.g.

struct Foo<T> {
    t: T,
}

impl Foo<i64> {
    pub fn hello(&self) {
        println!("i64 hello");
    }
}

impl Foo<u64> {
    pub fn hello(&self) {
        println!("u64 hello");
    }
}

However, is there some way in which I can also define a "catch-all" impl block for this struct - the one that should be called when hello() is not called with Foo<i64> or Foo<u64>. Something like:

struct Foo<T> {
    t: T,
}


impl Foo<i64> {
    pub fn hello(&self) {
        println!("i64 hello");
    }
}

impl Foo<u64> {
    pub fn hello(&self) {
        println!("u64 hello");
    }
}

imp<T> Foo<T> {
    pub fn hello(&self) {
        println!("generic hello");
    }
}

The second code snippet fails compilation with error: duplicate definitions for hello. Am I doing something syntactically incorrect here, or is it that this is something of an anti-pattern?

Hi, you can't do it yet, you have to wait for specialization. When it lands (or use nightly) you would use a trait and do something like this.

1 Like

thank you!