Sure, let's get started! Here's a step-by-step guide to writing a simple substring-match CLI app in Rust:
-
First, you'll need to install Rust if you haven't already. You can download it from the official website: https://www.rust-lang.org/tools/install
-
Once Rust is installed, open a terminal and create a new Rust project using Cargo, Rust's package manager:
cargo new substring_match_app
This will create a new directory called substring_match_app with some initial files and directories.
- Change into the new project directory:
cd substring_match_app
-
Open the src/main.rs file in a text editor. This is where we'll write our code.
-
We'll start by importing some Rust standard library modules we'll need:
use std::env;
use std::io::{self, Write};
The env module will allow us to access command-line arguments, and the io module will let us read and write to the console.
- Next, we'll define our
main function, which is the entry point of our program:
fn main() {
let args: Vec<String> = env::args().collect();
if args.len() < 3 {
eprintln!("Usage: {} <substring> <string>", args[0]);
std::process::exit(1);
}
let substring = &args[1];
let string = &args[2];
let result = match string.contains(substring) {
true => "Substring found",
false => "Substring not found",
};
println!("{}", result);
}
Let's break this down:
- We get the command-line arguments using the
env::args() function, which returns an iterator over the arguments. We collect them into a vector using the collect() method.
- We check that there are at least two arguments (the substring and string to search). If not, we print an