What is the idiomatic way to convey volatile meaning?

Am I missing or modifying arguments without a link that are not supported in Rust?

To give an example, I played with Rust and tried to implement the Euclidean algorithm for all numeric types, and ideally I just wanted to pass arguments by value and change them, but adding the mut keyword to the argument type is rejected by the compiler. Therefore, I have to declare a mutable copy of the argument as a prolog function. Is this idiomatic / effective?

 use std::ops::Rem; extern crate num; use self::num::Zero; pub fn gcd<T: Copy + Zero + PartialOrd + Rem<Output=T>>(a : T, b : T) -> T { let mut aa = a; let mut bb = b; while bb > T::zero() { let t = bb; bb = aa % bb; aa = t; } aa } 
+5
source share
1 answer

Of course, we can say that the argument will change:

 pub fn gcd<T>(mut a: T, mut b: T) -> T where T: Copy + Zero + PartialOrd + Rem<Output=T> { while b > T::zero() { let t = b; b = a % b; a = t; } a } 

Is [declaring a modified copy of the argument] idiomatic / efficient?

This should be good in terms of efficiency. The optimizer will see that they are the same and do not perform extraneous copying.

As for the idioms, I'm not sure. Initially, I started by not putting mut in the argument list of my function, since I felt that this was excessive implementation information. I am currently advancing and putting it there.

+9
source

All Articles