How to Build a CLI Program in Rust from Scratch

Are you tired of using clunky command line programs that lack efficiency and functionality? Do you want to create your own command line program that can make your life easier? If so, then you've come to the right place! Rust is a system programming language that is designed to be fast, reliable, and safe. With its strong emphasis on performance and safety, Rust is an excellent choice for building command line programs.

In this article, we'll show you how to build a CLI program in Rust from scratch. We'll cover everything from setting up your project to handling user input and creating output. So, grab your favorite beverage and let's get started!

Setting Up Your Rust Development Environment

Before we begin building our CLI program, we need to make sure that we have the necessary tools installed on our system. Here's what you'll need:

Once you have Rust and Cargo installed, you can check the version of Rust by opening up a terminal and typing the following command:

rustc --version

You should see a message that displays the installed version of Rust.

Creating a New Rust Project

Now that we have our development environment set up, we can create a new Rust project. Open up a terminal and navigate to the directory where you want to create your project. Once you're in the directory, run the following command:

cargo new mycli

This will create a new Rust project with the name mycli. You can replace mycli with any name that you prefer.

Understanding the Structure of a Rust Project

Before we dive into writing code, let's take a moment to understand the structure of a Rust project. When we created our project with Cargo, it generated a few files and directories for us. Here's what each file and directory does:

Parsing Command Line Arguments

One of the most important aspects of a command line program is its ability to handle user input. In Rust, we can use the clap library to parse command line arguments. clap is a powerful library that can handle a wide range of use cases. First, let's add clap as a dependency in our Cargo.toml file:

[dependencies]
clap = "2.33.0"

After adding clap as a dependency, we need to import it in our src/main.rs file:

extern crate clap;

use clap::{App, Arg};

Now that we've imported clap, let's define the command line arguments for our CLI program. We'll create a simple program that takes two arguments: a filename and a text input. Here's what our src/main.rs file should look like:

extern crate clap;

use clap::{App, Arg};

fn main() {
    let matches = App::new("My CLI Program")
        .version("1.0")
        .author("Your Name <you@example.com>")
        .about("A simple command line program in Rust")
        .arg(
            Arg::with_name("filename")
                .short("f")
                .long("file")
                .value_name("FILE")
                .help("The name of the file to write to")
                .takes_value(true),
        )
        .arg(
            Arg::with_name("text")
                .help("The text to write to the file")
                .required(true)
                .index(1),
        )
        .get_matches();

    let filename = matches.value_of("filename").unwrap_or("output.txt");
    let text = matches.value_of("text").unwrap_or_default();

    println!("Writing to file '{}' with text '{}'", filename, text);
}

Let's break down what's happening in this code. We first create a new App with the name "My CLI Program". We then set the version, author, and about information for our program. Next, we define two arguments using the Arg struct. The filename argument is optional and has a short -f and a long --file option. The text argument is required and doesn't have any options. We then call get_matches on our App to parse the command line arguments.

After parsing the arguments, we use unwrap_or and unwrap_or_default to set default values for the filename and text variables if they weren't specified by the user. Finally, we print out a message that shows the filename and text that we're writing to the file.

Creating Output

Now that we can parse command line arguments, let's create some output for our program. Rust has a built-in std::fs module that allows us to read and write files. Let's add some code to write to a file:

extern crate clap;

use clap::{App, Arg};
use std::fs::File;
use std::io::prelude::*; // Required for writing to files

fn main() {
    let matches = App::new("My CLI Program")
        .version("1.0")
        .author("Your Name <you@example.com>")
        .about("A simple command line program in Rust")
        .arg(
            Arg::with_name("filename")
                .short("f")
                .long("file")
                .value_name("FILE")
                .help("The name of the file to write to")
                .takes_value(true),
        )
        .arg(
            Arg::with_name("text")
                .help("The text to write to the file")
                .required(true)
                .index(1),
        )
        .get_matches();

    let filename = matches.value_of("filename").unwrap_or("output.txt");
    let text = matches.value_of("text").unwrap_or_default();

    let mut file = File::create(filename).expect("Unable to create file");

    file.write_all(text.as_bytes())
        .expect("Unable to write to file");

    println!("Successfully wrote to file '{}'", filename);
}

We've added the following lines of code to our main function:

Conclusion

Congratulations! You've just built a CLI program in Rust from scratch. We covered a lot of ground in this article, from setting up your development environment to parsing command line arguments and creating output. We hope that this has been a helpful guide to getting started with Rust command line programming.

Remember, this is just the beginning. Rust is a powerful language with a lot of features that can make your command line programs even more efficient and powerful. We encourage you to keep exploring the possibilities of Rust and to continue building amazing command line programs that make your life easier.

Thanks for reading and happy coding!

Editor Recommended Sites

AI and Tech News
Best Online AI Courses
Classic Writing Analysis
Tears of the Kingdom Roleplay
Open Models: Open source models for large language model fine tuning, and machine learning classification
Play RPGs: Find the best rated RPGs to play online with friends
Learn Dataform: Dataform tutorial for AWS and GCP cloud
Rust Guide: Guide to the rust programming language
Developer Levels of Detail: Different levels of resolution tech explanations. ELI5 vs explain like a Phd candidate