• Что бы вступить в ряды "Принятый кодер" Вам нужно:
    Написать 10 полезных сообщений или тем и Получить 10 симпатий.
    Для того кто не хочет терять время,может пожертвовать средства для поддержки сервеса, и вступить в ряды VIP на месяц, дополнительная информация в лс.

  • Пользаватели которые будут спамить, уходят в бан без предупреждения. Спам сообщения определяется администрацией и модератором.

  • Гость, Что бы Вы хотели увидеть на нашем Форуме? Изложить свои идеи и пожелания по улучшению форума Вы можете поделиться с нами здесь. ----> Перейдите сюда
  • Все пользователи не прошедшие проверку электронной почты будут заблокированы. Все вопросы с разблокировкой обращайтесь по адресу электронной почте : info@guardianelinks.com . Не пришло сообщение о проверке или о сбросе также сообщите нам.

Build Your First Rust CLI Tool: A Beginner-Friendly Walkthrough

Lomanu4 Оффлайн

Lomanu4

Команда форума
Администратор
Регистрация
1 Мар 2015
Сообщения
1,481
Баллы
155
Command-line tools are a great way to automate tasks, process data, or even just have fun with small utilities. Rust is an excellent language for this because it compiles to fast, standalone binaries with no runtime dependency and offers strong safety guarantees.

In this article, we’ll walk through building a simple CLI tool in Rust that reads a file and counts the number of words—similar to the Unix wc command.

Step 1: Set Up Your Project


Start by creating a new binary project:


cargo new wordcount --bin
cd wordcount

This gives you a working Rust project with src/main.rs as your entry point.

Step 2: Parse Command-Line Arguments


To keep things simple, we'll use the built-in std::env module to fetch the file path from the command line:


use std::env;
use std::fs;

fn main() {
let args: Vec = env::args().collect();

if args.len() < 2 {
eprintln!("Usage: wordcount ");
std::process::exit(1);
}

let filename = &args[1];
let contents = fs::read_to_string(filename)
.expect("Something went wrong reading the file");

let word_count = contents.split_whitespace().count();
println!("Word count: {}", word_count);
}
Step 3: Build and Test It


Build the project:


cargo build --release

Try it out:


./target/release/wordcount sample.txt

If everything works, you should see the number of words printed to the terminal.

Use Case Scenario


Imagine you're managing hundreds of text-based logs generated daily by a data pipeline. Manually reviewing them is inefficient. A fast CLI tool like this one can help you quickly analyze the logs—perhaps to find the lengthiest reports, flag empty files, or identify unusually verbose entries. With minimal setup, you can extend the tool to scan directories, summarize data, or even integrate into shell scripts. The result is better visibility into your data with significantly reduced manual effort—saving both time and cognitive load in your workflow.

✅ Pros and ❌ Cons of Using Rust for CLI Tools


✅ Pros:

  • ⚡ Blazing fast binaries
  • ? Memory safety without garbage collection
  • ? Great ecosystem with crates like clap, serde, and anyhow
  • ? Easy to write tests and CI integration

❌ Cons:

  • ? Steep learning curve for beginners
  • ⏱ Compile times can get long on larger projects
  • ? Advanced tasks (like TUI or async IO) require extra learning
Summary


You’ve just built your first real CLI tool in Rust! While this example is simple, it demonstrates core concepts: parsing input, reading files, and producing useful output. Rust's type system, safety, and performance make it a compelling choice for building CLI tools of any size.

Want to go further? I’ve written a concise, 15-page PDF guide that walks you through crafting professional tools from start to finish—including input parsing, formatting, file handling, and distribution:


Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

— just $5.

If this was helpful, you can also support me here:

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

☕


Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

 
Вверх Снизу