Rust, compute gcd: modularity, references This is my first time trying Rust. I wrote this code to compute the greater common divisor of 2 integers. Any advice to improve it? Am I using modularity/reference/borrow/dereference the correct way?

File src/gcd.rs:

// calculate the gcd of two integers
// https://en.wikipedia.org/wiki/Greatest_common_divisor

pub fn gcd(a: &amp;i64, b: &amp;i64) -&gt; i64 {
    let mut _a = *a;
    let mut _b = *b;
    while _b != 0 {
        let tmp = _a;
        _a = _b;
        _b = tmp % _b;
    }
    _a
}

#[cfg(test)]
mod tests {
    use ::gcd;

    #[test]
    fn test_gcd() {
        assert_eq!(gcd::gcd(&amp;60, &amp;168), 12);
        assert_eq!(gcd::gcd(&amp;1071, &amp;1029), 21);
    }
}


File src/main.rs:

mod gcd;

fn main() {
    println!("gcd({}, {}) = {}", 60, 168, gcd::gcd(&amp;60, &amp;168)); 
}


Directory structure:

$ tree
.
├── Cargo.lock
├── Cargo.toml
├── src
│   ├── gcd.rs
│   └── main.rs
└── target
    ├── ...
You do not need to take the numbers by reference.
Do not put an underscore at the beginning of the variable name. A variable name beginning with _ is used to say to the compiler that the variable is unused.


Otherwise, I see no issues in your code. Here is the solution taking account of my comments:

pub fn gcd(mut a: i64, mut b: i64) -&gt; i64 {
    while b != 0 {
        let tmp = a;
        a = b;
        b = tmp % b;
    }
    a
}

#[cfg(test)]
mod tests {
    use ::gcd;

    #[test]
    fn test_gcd() {
        assert_eq!(gcd(60, 168), 12);
        assert_eq!(gcd(1071, 1029), 21);
    }
}


Further explanations:


  Why do I need to use let a = instead of let mut a = when calling it?


Not sure if my explanation is legit, but when you give a thing to another function, this function can do whatever it wants to this thing: it can take it as mutable or not. That is not anymore the problem of the previous owner.


  Which type of variables should and should not be passed by reference?


This is a very broad question. I advice you to think things differently. In Rust, you can give a thing, or only lend it (the thing is borrowed). The general answer is: if you do not need anymore the thing, or if the receiver needs a full control on it, give it away.

In this specific case, the thing is copyable and small (as small as a reference, in fact). So, borrow it does not give any advantage: just take it (or take a copy) and do not bother with references.