Impl for Struct that uses Generics and associated methods that doesn't use the generic

So I have a struct like this which uses a generic.

Then I have an impl block like this
image

I have added a method to the struct that does not use the generic at all.
image

But my linter tells me I still have to specify the generic field when calling this method through my struct. So it ends up looking something like this.
image

Is there any way I can still have the function associated with the struct without having to specify the generic like this in the function call? I would like it to look like Matrix::permutations(&numbers); instead of Matrix::<f32>::permutations(&numbers).

Please post code as actual text, not as images of code.

As to your actual question, if this is just an associated method that doesn't take or return a Matrix, why associate it with Matrix in the first place? Why not just make it a normal function?

2 Likes

Because conceptually I group them together and would like to call the method under the name of the struct.

There are no such struct.Matrix<f32> or Matrix<f64> are things, but Matrix is not a thing.

Sometimes compiler can deduce the omitted part, but in your example you don't give it any information about how to do that.

How would one know that? It's in the impl<F: Float + Copy> block, which means that it can use F, even is indirectly. It may create variables of type F, it may create Matrix<F> and so on.

You wouldn't know whether it uses F or not till you look on the implementation… and the whole point of the interface is to ensure that you don't need to do that.

1 Like

Is there any way to get the compiler to deduce that the default generic should be f32? Or is that not possible with rust yet?

Also, It does not let me define an impl block without the generic...

Sure, syntax is struct Matrix<F: Float = f32>

But you couldn't do that on per-impl block, it's global decision.

1 Like

Of course, because you wouldn't be able to use it like that. Matrix is not a thing! Compiler needs to always know which Matrix you want.

1 Like

Thank you, it is nice to know about default generic feature. Your explanation makes sense and I know some workarounds to this issue, associating it with non-generic struct, associating it with a module... I appreciate your help :smiley: .

Another workaround is to put the associated function in an impl with concrete types in the parameter position instead of generics.

impl Matrix<f32> {
    pub fn permutations(..)
}

In fact, that's also a workaround for getting around the limitations of defaulted parameters. Using Matrix<F = f32> won't make Matrix::permutations work because that's syntactic sugar for Matrix::<_>::permutations. However, it will make <Matrix>::permutations work.

3 Likes

Thank you for the other workaround. Your link was a nice read and great job with your learning blogs.

1 Like