Is there a trait for primitive coercion?

Lets say I have the following struct:

struct Weight<W> {
    a: W,
    b: W,
}

And I wish to implement a method for any generic W that can be coerced into an `f32. Rather than the following:

impl Weight<u32> {
    fn do_thing(&self) -> f32 {
        self.a as f32 / self.b as f32
    }
}

impl Weight<usize> {
    //...
}

Is there an implementation I can do for W where it is a primitive that can be cast as an f32? E.g.

impl<W> Weight<W> 
    where W: <W as f32> // <- obviously not a trait
{
    fn do_thing(&self) -> f32 {
        self.a as f32 / self.b as f32
    }
}

Just a note, other avenues I looked at was Into<f32>, and a trait similar to FloatToInt however I could not find one, and that trait is experimental anyway. Is manually implementing for each type the only option in such a case?

Rust Playground

FYI it's a generic struct or in the right company, a type constructor. Traits are something else.

Thanks for the correction. That was definently left over while formatting my question as I have never heard of a "trait struct" either. :laughing:

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.