Confusion on implementing Add_Assign on struct

I am working on creating a custom generic type similar to Wrapping<T> that allows specifying a maximum and minimum bound and wrapping within that inclusive range.

My code so far is here which is a modified copy of the source of the Wrapping<T> from the main rust source code. I haven't cleaned up the documentation yet, so please ignore that.

My intention is to swap this for some locations in another project that currently use Wrapping<T> and a mod operation for the range restriction, but I wanted the restriction to come from the type so I don't forget to add the mod.

I implemented all the normal math operation traits, and even used the forward_ref* macros to try and resolve some potential headaches.

I am still having an issue when trying to add_assign my RangedWrapping<T,U> type when it is the type of a struct field.

When creating a normal variable, the add_assign works just fine, but as soon as I try and use it on a struct field, I get the following error:

binary assignment operation += cannot be applied to type RangedWrapping<usize, usize>

I have been googling my fingers off, and can't find an explanation for why normal variables work, but not struct fields, especially since Wrapping<T> works in the same scenario.

Thanks in advance.

I'm pretty sure it's because you've put this bound everywhere:

    T: Add<i32, Output = T>,
    U: Add<i32, Output = T>,

You only actually use it in fn wrap, I think, to add 1. See if you can use something like num_traits::One instead.

Playground with the bounds removed and wrap hackily modified (not a proper fix).

And I'm pretty sure your "creating a normal variable" cases work because they all just create a RangedWrapping<i32, i32>, satisfying the bound.

1 Like

Thank you. the Add<i32, Output = T> was indeed the issue. I just had to remember to remove the trait bound from all the trait implemnetations, and not just wrap().

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.