#Trait fn for specific associated type

6 messages · Page 1 of 1 (latest)

marble peak
#

Basically, I'm looking for a way to have a trait method that is only valid for specific assoc types.
I've done something similar to here to get it to work for default impl: https://stackoverflow.com/q/64100386

However, I'm struggling to get it to work when I don't want to use the default impl. It appears that the trait bound isn't applying to the input, just the output of the function. Any ideas how to get around this?

Playground link
Code:

trait MyTrait {
    type Datatype;

    fn do_something(&self) -> Self::Datatype
    where
        Self: MyTrait<Datatype = f64>,
    {
        0.0
    }
}

struct MyStruct<T>(T);

impl<T> MyTrait for MyStruct<T> {
    type Datatype = T;

    fn do_something(&self) -> Self::Datatype
    where
        Self: MyTrait<Datatype = f64>,
    {
        self.0
    }
}
river parcel
#

an extension trait would probably be better here
this compiles: ```rs
trait DoSomething: MyTrait<Datatype = f64> {
fn do_something(&self) -> Self::Datatype;
}

impl DoSomething for MyStruct<f64> {
fn do_something(&self) -> Self::Datatype {
self.0
}
}

marble peak
#

Hmm, that might work. I unfortunately lose the default implement though unfortunately,

#

As something like this will have conflicting impl

#

It'd be nice if I got it for free for anything that impl MyTrait, but still be able to override if desired

#

More like this, ```rs

trait MyTrait {
type Datatype;

}

trait DoSomething: MyTrait<Datatype = f64> {
fn do_something(&self) -> Self::Datatype
{
0.0
}
}

impl<S: MyTrait<Datatype = f64>> DoSomething for S {}

struct MyStruct<T>(T);

impl<T> MyTrait for MyStruct<T> {
type Datatype = T;
}

impl DoSomething for MyStruct<f64> {
fn do_something(&self) -> f64 {
self.0
}
}