Define "common type" inside a trait

struct Foo{
    
}

struct Bar{
    
}

trait Interface{
    type Ret;
    fn setup()->Self::Ret;
    
}

impl Interface for Foo{
    type Ret = i32;
    fn setup()->Self::Ret{
        println!("Foo::setup()");
        1
    }
}

impl Interface for Bar{
    type Ret = i32;
    fn setup()->Self::Ret{
        println!("Foo::setup()");
        1
    }
}

In the above code I have a common type (which is Ret) which is part of trait Interface . My question is- since Ret is a common type and specifying the same type in multiple impls doesn't look good. So is there any possible way I can define this in trait itself. AFAIK this gives compilation error . what do you think which way is better to avoid specifying the same type in multiple impls .

Why do you use the associated type at the first place? Why can't your setup be defined as returning i32 directly?

1 Like

Is this what you want?

trait Interface{
    fn setup() -> i32;
}
1 Like

Either nightly Rust and #![feature(associated_type_defaults)] or no way, imho:

#![feature(associated_type_defaults)]

struct Foo {}

struct Bar {}

trait Interface {
    type Ret = i32;
    fn setup() -> Self::Ret;
}

impl Interface for Foo {
    fn setup() -> Self::Ret {
        println!("Foo::setup()");
        1
    }
}

impl Interface for Bar {
    fn setup() -> Self::Ret {
        println!("Foo::setup()");
        1
    }
}

fn main() {
    println!("Hello, world!");
}

Playground

1 Like

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.