daniellga
daniellga

Reputation: 1224

Implement function for a struct returning a specific generic type

I am trying to return exclusively a f32 in my new function, inside an impl for Test struct. I am sure this isn't the best way to do it since I can call it with any type I want in the turbofish. Could you suggest me a better way of doing the same thing keeping the function as an impl of Test? Thanks.

use std::path::Path;

fn main() {
    #[derive(Debug)]
    struct Test<T> {
        field: T
    }
    
    impl<T> Test<T> {
        fn new() -> Test<f32> {
            Test{field: 3_f32}
        }
    }
    
    let b = Test::<i16>::new(); // i16 or i32 or whatever
    println!("{:?}", b);
}

Upvotes: 0

Views: 48

Answers (1)

Kevin Reid
Kevin Reid

Reputation: 43733

Your struct is generic, but your impl doesn't have to be.

impl Test<f32> {
    fn new() -> Self {
        Test { field: 3. }
    }
}

Now, Test::new() will compile without any turbofish and the type is always Test<f32>.

Upvotes: 3

Related Questions