Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support in-place negation/reciprocal operations #438

Open
mozhewen opened this issue Aug 22, 2024 · 1 comment
Open

Support in-place negation/reciprocal operations #438

mozhewen opened this issue Aug 22, 2024 · 1 comment

Comments

@mozhewen
Copy link

Big numbers are often stored in some data structure such as values of a BTreeMap. When I want to do some local change on the data structure, I usually get a &mut of the number. In this case, if I'm taking a neg(), a clone() of the number is needed, which is inefficient since it's essentially only a flip of sign. Similar for recip().

A new function like

fn set_neg(&mut self) {
    self.sign = -self.sign;
}

may be helpful. In fact, I even think it should be a method of the Neg trait.

@cuviper
Copy link
Member

cuviper commented Sep 6, 2024

If this is for a type that you control, you can certain add such a method directly. The num traits are mostly for generics where you don't know or control the particular numeric type.

Even for generics, you can already write something like this:

fn foo<T: Zero + Neg<Output = T>>(x: &mut T) {
    *x = -mem::replace(x, T::zero());
}

This assumes that zero is cheap to create and drop, but that's usually true.

In fact, I even think it should be a method of the Neg trait.

That would have to be a proposal for the standard library. When extending an existing trait, we also need a default implementation, and in that context I'd probably write it similar to what I wrote above, but add where Self: Default to the method and use mem::take instead of Zero.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants