ilmoi
ilmoi

Reputation: 2534

How do I write a trait to mutate an integer in place?

I'm trying to implement a trait for integers that adds a value to themselves.

My failing attempt so far:

impl TryAdd for u128 {
    fn try_add(self, rhs: Self) -> Result<Self, ProgramError> {
        self.checked_add(rhs).ok_or(SomeError::BadError.into())
    }
    fn try_self_add(mut self, rhs: Self) -> ProgramResult {
        self = self.try_add(rhs)?;
        Ok(())
    }
}

The first function works as expected, returning a new integer with rhs added. The second function currently doesn't work.

What I'd like it to do:

#[test]
fn test_self_add() {
    let x = 10;
    let y = 2;
    x.try_self_add(y).unwrap();
    assert_eq!(x, 12);
}

Is there a way to accomplish this?

Upvotes: 1

Views: 212

Answers (1)

Hauleth
Hauleth

Reputation: 23566

In try_self_add you modify copy of the value instead of the value itself, so it is expected behaviour (that is also why x in test do not need to be mut). What you really want is:

fn try_self_add(&mut self, rhs: Self) -> ProgramResult {
    *self = self.try_add(rhs)?;
    Ok(())
}

With such alteration it works as expected.

Upvotes: 4

Related Questions