Rusty Projects — Chapter 01

Yen
Rustaceans
Published in
3 min readMay 10, 2024

--

Practice Rust with several projects | Creative Projects for Rust Programmers
By Carlo Milanesi.

This is the note of code examples from the book and the implemented results.

Catalogue

  • Result / ? Operator
  • Pseudo-random number generator
  • Parsing the command line

? Operator / Result

Further information | Rust Doc

fn main() -> Result<(), usize> {
let array = [12, 19, 27];
let found = array.binary_search(&19)?;
println!("Found {}", found);
let found = array.binary_search(&20)?;
println!("Found {}", found);
Ok(())
}

Pseudo-random number generators

main.rs

// Declare basic functions for pseudo-random number generators.
use rand::prelude::*;
fn main() {
// Create a pseudo-Random Number Generator for the current thread
let mut rng = thread_rng();
// Print an integer number
// between 0 (included) and 20 (excluded).
println!("{}", rng.gen_range(0, 20));
// Print a floating-point number
// between 0 (included) and 1 (excluded).
println!("{}", rng.gen::<f64>());
// Generate a Boolean.
println!("{}", if rng.gen() { "Heads" } else { "Tails" });
}

Cargo.toml

[package]
name = "use_rand"
version = "0.1.0"
authors = []
edition = "2018"

[dependencies]
rand = "0.6"

Parsing the command line

main.rs

use std::path::PathBuf;
use structopt::StructOpt;

#[derive(StructOpt, Debug)]
struct Opt {
/// Activate verbose mode
#[structopt(short = "v", long = "verbose")]
verbose: bool,

/// File to generate
#[structopt(short = "r", long = "result", parse(from_os_str))]
result_file: PathBuf,

/// Files to process
#[structopt(name = "FILE", parse(from_os_str))]
files: Vec<PathBuf>,
}

fn main() {
println!("{:#?}", Opt::from_args());
}

Cargo.toml

[package]
name = "use_structopt"
version = "0.1.0"
authors = ["carlomilanesi"]
edition = "2018"

[dependencies]
structopt = "0.2"

Type this in terminal

cargo run input1.txt input2.txt -v --result

Result

Result

Hey Rustaceans!

Thanks for being an awesome part of the community! Before you head off, here are a few ways to stay connected and show your love:

  • Give us a clap! Your appreciation helps us keep creating valuable content.
  • Become a contributor! ✍️ We’d love to hear your voice. Learn how to write for us.
  • Stay in the loop! Subscribe to the Rust Bytes Newsletter for the latest news and insights.
  • Support our work!Buy us a coffee.
  • Connect with us: X

--

--

Yen
Rustaceans

Programming is a mindset. Cybersecurity is the process. Focus on Python & Rust currently. More about me | https://msha.ke/monles