Rust Code Snippets

Below are some useful Rust code snippets for use in everyday projects.

When dealing with directories and files it may be necessary to check for their existence. Below is an example of how to do this.

use std::path::Path;

fn main() {

    // Example directory and file.
    let example_directory = "C:\\demo\\";
    let example_file = "C:\\demo\\demo.txt";

    // Check if the directory exists.
    if Path::new(example_directory).is_dir()
    {
        println!("The directory '{}' exists.", example_directory);   
    }
    else
    {
        println!("The directory '{}' doesn't exist.", example_directory);  
    }

    // Check if the file exists.
    if Path::new(example_file).is_file()
    {
        println!("The file '{}' exists.", example_file);
    }
    else
    {
        println!("The file '{}' doesn't exist.", example_file);
    }

}

Here is an example of how to generate a random number between two values, in this case 1 and 59, then display it.

use rand::Rng;

fn main() {

    // Minimum and maximum values for random number.
    let min_val = 1;
    let max_val = 59;

    // Generate random number.
    let mut rng = rand::thread_rng();
    let random_number = rng.gen_range(min_val..max_val+1);

    // Display the result in the console or terminal.
    println!("{}", random_number);

}

A text file can be read from and processed line by line.

use std::fs::File;
use std::io::{BufRead, BufReader};

fn main() {

    // Open file and assign it to a reader object.
    let file = File::open("C:\\demo\\demo.txt").unwrap();
    let reader = BufReader::new(file);

    // Process the lines in the file.
    for line in reader.lines()
    {
        // Display the line in the console/terminal.
        println!("{}", line.unwrap());
    }

}