JANUARY 17, 2024

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

The simplest Rust program

fn main() {
    println!("Hello, World!");

You can compile this program with rustc.


Then run it.

# Hello, World!

A program that counts words in files concurrently

I generated this program with ChatGPT and then modified it.

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();

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),

    for handle in handles {

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.

# file2.txt has 45 words.
# file3.txt has 1324 words.
# file1.txt has 93980 words.

Want to see older publications? Visit the archive.

Listen to Getting Simple .