rust

During processing command line arguments, trouble with function Calculates the Greatest Common Divisor cannot find function `gcd` in this scope


During processing command line arguments, I've got a trouble with function Calculates the Greatest Common Divisor (GCD)

I am reading the O'Reilly book Programming Rust by Jim Blandy & Jason Orendoff.

On page 28 on chapter "processing command line arguments"

I am made such programm

use std::io::Write;
use std::str::FromStr;
fn main() {
    let mut numbers = Vec::new();
    for arg in std::env::args().skip(1) {
        numbers.push(u64::from_str(&arg).expect("error parsing argument"));
    }
    if numbers.len() == 0 {
        writeln!(std::io::stderr(), "Usage: gcd NUMBER ...").unwrap();
        std::process::exit(1);
    }
    let mut d = numbers[0];
    for m in &numbers[1..] {
        d = gcd(d, *m);
    }
    println!("The greatest common divisor of {:?} is {}", numbers, d);
}

But already got such mistake:

error[E0425]: cannot find function `gcd` in this scope
  --> new.rs:15:12
   |
15 |              d = gcd(d,*m);
   |                  ^^^ not found in this scope

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0425`.

What must I do to correct this mistake?


Solution

  • The function gcd is not defined in the code you gave above, which is what the compiler is complaining about.

    In the book you mentioned, the function is defined at the beginning of the previous chapter "Rust Functions". You'll need to add the function to your program's code.

    // As given by Programming Rust, page 8, "Rust functions"
    fn gcd(mut n: u64, mut m: u64) -> u64 {
        assert!(n != 0 && m != 0);
        while m != 0 {
            if m < n {
                let t = m;
                m = n;
                n = t;
            }
            m = m % n;
        }
        n
    }