Simplifying recurring generics

I'm making progress with generics and lifetimes - I can get things to compile now!

However I'm looking at the ergonomics of some of the calls and wondering if I'm missing a structuring trick.

Essentially I have a data structure and the type of data that I want to be generic over. See the example below where I create a struct Test of usize.

What is bugging me is the call example::<usize, Test::<usize>>(test) where it feels like the double mention of usize is redundant.

Is there a way of configuring the function so it could be example::<Test::<usize>>(test) or example::<usize, Test>(test)

EDIT: as I wrote this I remembered the _ symbol and I can see that example::<usize, Test::<_>>(test) and actually I can leave the definitions out alltogether for the type system to infer. I'll have to go back to my original code and see if this applies.


trait TestTrait<T> {
    fn do_something() -> Self;
}

struct Test<T> {data: Option<T>}

impl<T> TestTrait<T> for Test<T> {
    fn do_something() -> Self {
        return Self {data: None}
    }
    
}

fn example<T,S>(data: S) where
T: Copy,
S: TestTrait<T>
{
    S::do_something();
    
}

fn main() {

    let test = Test::<usize>::do_something();
    example::<usize, Test::<usize>>(test)
}

(Playground)

In this case you can even

fn main() {
    let test = Test::<usize>::do_something();
    example(test)
}

Or alternatively

fn main() {
    let test: Test<usize> = TestTrait::do_something();
    example(test)
}

As once the type of test is known, the compiler can infer which monomorphized example function to call.

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.