[Book] Programming Rust

First Post:

Last Update:

Word Count:
333

Read Time:
2 min

El libro

Introduction

This article is used to keep notes and summaries of the book “Programming Rust”.
The content will be continuously updated as I read through the book.

Reflection

Chapter.2 - A Tour of Rust

rustup and Cargo

1
2
3
4
5
cargo --version

rustc --version

rustdoc --version
1
cargo new hello
1
cargo run

Rust Functions

1
2
3
4
5
6
7
8
9
10
11
12
13
14
fn gcd(mut n: u64, mut m:64) -> u64 {
assert!(n != 0 && m != 0);
while m != 0 {
if m < n {
let t = m;
m = n;
n = t;
}

m = m % n;
}

n
}

By default, once a variable is initialized, its value can’t be changed, but placing the mut keyword before the praameters n and m allows our function body to assign to them.

The function’s body starts with a call to the assert! macro, verifying that neither argument is zero. The ! character marks this as a marco invocation, not a function call.

Writing and Running Unit Tests

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

The #[test] marker is an example of an attribute. Attributes are an open-ended system for marking functions and other declarations with extra information, like attributes in C++ and C#, or annotations in Java. They’re used to control compiler warnings and code style checks, include code conditionally (like #ifdef in C and C++), tell Rust how to interact with code written in other languages, and so on.

Handling Command-Line Arguments

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
use std::str::FromStr;
use std::env;

fn main() {
let mut numbers = Vec::new();
for arg in env::args().skip(1) {
numers.push(u64::from_str(&arg).expect("error parsing argument"));
}

if numbers.len() == 0 {
eprintln!("Usage: gcd NUMBER ...");
std::process::exit(1);
}

let mut d = number[0];
for m in &numbers[1..] {
d = gcd(d, *m);
}

println!("The greatest common divisor of {:?} is {}", numbers, d);
}