0

I have a struct I need to implement multiplication for. The multiplication can either be with a value I can turn into some scalar (i8, usize etc.) or the same as the struct

struct Eg<const N: usize, T> ([T; N]);

impl<const N: usize, T, Q> std::ops::Mul<Q> for Eg<N, T> where Q: From<isize> { 
    type Output = Self;

    fn mul(self, rhs: Q) -> Self::Output { }
}

impl<const N: usize, const P: usize, T> std::ops::Mul<Eg<P, T>> for Eg<N, T> { 
    type Output = Eg<P, T>;

    fn mul(self, rhs: Self) -> Self::Output { }
}

Since Eg does not implement From<isize> the compiler would have to chose use the second option. Rust isn't a fan of this and says there are conflicting implementations of trait 'std::ops::Mul'.

I am aware of this question. This has not been updated (aside for editing) for over 8 years and I assume things will have changed since then

If there's any way I can specify what implementation the compiler looks at for specific multipliers (rhs) that would be very helpful. Thanks


The full code is fairly large and would be less helpful here than the sample given. the main points (I think) are still maintained:

  • Different number of constants for rach implementation (with a different number of generics in the full code)
  • Different output types
  • Differet multiplier types (Q vs Eg<P, T>)
nxe
  • 241
  • 2
  • 9
  • What is `Q`? I don't see it declared. – Chayim Friedman Aug 15 '22 at 00:02
  • The second `impl` also has a generic parameter `N` that is not used anywhere in either the trait or the type it's being implemented on, which is disallowed -- there would be no way to specify this parameter in usage of the implementation. – cdhowie Aug 15 '22 at 02:03
  • Sorry. Missed them out. The code should be correct now – nxe Aug 15 '22 at 16:31
  • `Q` is still not declared on the second `impl`. – Chayim Friedman Aug 17 '22 at 09:36
  • `Q` shouldn't really have been there sorry – nxe Aug 18 '22 at 18:17
  • I was not able to reproduce, your code seems to compile just fine: [playground](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=f22b053afc4901289f0366fd56bc4db3). The linked Q&A is still the behavior but isn't applicable here because that is due to constraints for *foreign* types. Your `Eg` type is local and the compiler is plainly able to see that `From` is not implemented. – kmdreko Sep 20 '22 at 19:40

0 Answers0