Visit homepage

Hello, Rust

  • Planted:

I just wrote my first Rust program. Er, it’s not really even my program—I just read an example from a book, tried to implement it from memory a few minutes later, ran cargo run, then used hints from the Rust compiler to fix my code. First impression…the hints are really good!

Here’s the function:


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
}

I’m starting with O’Reilly’s Programming Rust, but I plan to go through The Book in parallel and see what sticks.

I also wrote copied my first test in Rust, which quickly caught a bug in my greatest common divisor implementation.


#[test]
fn test_gcd() {
assert_eq!(gcd(14, 15), 1);
assert_eq!(gcd(2 * 3 * 5 * 11 * 13, 3 * 7 * 11 * 19), 3 * 11);
}

It's pretty nice that cargo includes tests out of the box without having to install a dependency.

Backlinks

Reply

Respond with your thoughts, feedback, corrections, or anything else you’d like to share. Leave your email if you’d like a reply. Thanks for reading.