Nono.MA

Compile and run Rust

JANUARY 17, 2024

Here are two simple Rust programs and how to compile and run them in macOS with rustc.

The simplest Rust program

// first.rs
fn main() {
    println!("Hello, World!");
}

You can compile this program with rustc.

rustc first.rs

Then run it.

./first
# Hello, World!

A program that counts words in files concurrently

I generated this program with ChatGPT and then modified it.

// count.rs
use std::fs::File;
use std::io::{self, BufRead};
use std::path::Path;
use std::thread;

fn count_words_in_file(file_path: &Path) -> io::Result<usize> {
    let file = File::open(file_path)?;
    let reader = io::BufReader::new(file);

    let mut count = 0;
    for line in reader.lines() {
        let line = line?;
        count += line.split_whitespace().count();
    }
    Ok(count)
}

fn main() {
    let file_paths = vec!["file1.txt", "file2.txt", "file3.txt"]; // Replace with actual file paths
    let mut handles = vec![];

    for path in file_paths {
        let path = Path::new(path);
        let handle = thread::spawn(move || {
            match count_words_in_file(path) {
                Ok(count) => println!("{} has {} words.", path.display(), count),
                Err(e) => eprintln!("Error processing file {}: {}", path.display(), e),
            }
        });
        handles.push(handle);
    }

    for handle in handles {
        handle.join().unwrap();
    }
}

We then build and run as before, assuming we have three text files (file1.txt, file2.txt, and file3.txt) in the same directory of our program.

rustc count.rs
./count
# file2.txt has 45 words.
# file3.txt has 1324 words.
# file1.txt has 93980 words.

BlogCodeRustRustc