Learning rust
I bought The Rust Programming Language in ePub format a long time ago.
It has been on my radar for a few years now, but I never had the time to learn it.
Install
$ curl --proto '=https' --tlsv1.2 https://sh.rustup.rs -sSf | sh
The recommended method did not work for me.
The debian way did work:
$ sudo apt install rust-all cargo
...
$ rustc --version
rustc 1.85.0 (4d91de4e4 2025-02-17) (built from a source tarball)
Chapter 1.2
The famous Hello, World! program:
// See: https://doc.rust-lang.org/stable/book/ch01-02-hello-world.html
fn main() {
println!("Hello, world!");
}
Chapter 1.3
Hello, World! the cargo way:
cees@dev01:~/prj/hello-cargo$ cargo build
Compiling hello-cargo v0.1.0 (/home/cees/prj/hello-cargo)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.20s
cees@dev01:~/prj/hello-cargo$ ./target/debug/hello-cargo
Hello, world!
cees@dev01:~/prj/hello-cargo$ cargo run
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.00s
Running `target/debug/hello-cargo`
Hello, world!
Chapter 2: Guessing game
See: The Rust Programming Language: Chapter 2
use std::cmp::Ordering;
use std::io;
use rand::Rng;
fn main() {
println!("Guess the number!");
let secret_number = rand::rng().random_range(1..=100);
// println!("The secret number is: {secret_number}");
loop {
println!("Please input your guess.");
let mut guess = String::new();
io::stdin()
.read_line(&mut guess)
.expect("Failed to read line");
let guess: u32 = match guess.trim().parse() {
Ok(num) => num,
Err(_) => continue,
};
println!("You guessed: {guess}");
match guess.cmp(&secret_number) {
Ordering::Less => println!("Too small!"),
Ordering::Greater => println!("Too big!"),
Ordering::Equal => {
println!("You win!");
break;
}
}
}
}
N.B. the syntax of rand::Rng has changed.
cees@dev01:~/prj/guessing-game$ cargo run
Compiling guessing-game v0.1.0 (/home/cees/prj/guessing-game)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.27s
Running `target/debug/guessing-game`
Guess the number!
Please input your guess.
50
You guessed: 50
Too small!
Please input your guess.
75
You guessed: 75
Too big!
Please input your guess.
63
You guessed: 63
Too big!
Please input your guess.
57
You guessed: 57
You win!