พัฒนา CLI Tools ที่เร็วและปลอดภัยด้วย Rust

Sharing is caring!

📌 ทำไม Rust ถึงเหมาะกับการสร้าง CLI Tools?

Rust เป็นภาษาที่โดดเด่นในเรื่องความเร็วและความปลอดภัยแบบ zero-cost abstraction ทำให้มันเป็นตัวเลือกยอดนิยมสำหรับการพัฒนา Command-Line Interface (CLI) tools ที่ทำงานเร็ว มีขนาดเล็ก และไม่มี runtime overhead เหมือนกับภาษาอื่น ๆ เช่น Python หรือ Node.js

🚀 เริ่มต้นโปรเจค CLI Tool

สร้างโปรเจคใหม่ด้วย cargo:

cargo new cli-fast-tool
cd cli-fast-tool
  

📦 ใช้ crate ยอดนิยม: clap

เพิ่ม dependency clap เพื่อจัดการ arguments:




[dependencies]

clap = { version = “4”, features = [“derive”] }

🧪 โค้ด CLI Tool เบื้องต้น

use clap::Parser;

/// CLI ตัวอย่าง
#[derive(Parser, Debug)]
#[command(author, version, about)]
struct Args {
    /// ชื่อของผู้ใช้
    #[arg(short, long)]
    name: String,
}

fn main() {
    let args = Args::parse();
    println!("สวัสดีคุณ {}!", args.name);
}
  

🛠 เพิ่ม Subcommand และ Flag

#[derive(Parser)]
#[command(name = "tools")]
enum Command {
    Hello {
        #[arg(short, long)]
        name: String,
    },
    Sum {
        #[arg()]
        a: i32,
        #[arg()]
        b: i32,
    },
}

fn main() {
    match Command::parse() {
        Command::Hello { name } => println!("Hello, {}!", name),
        Command::Sum { a, b } => println!("Sum = {}", a + b),
    }
}
  

📂 จัดโครงสร้าง CLI ที่ดี

สามารถแยกโค้ดออกเป็นไฟล์ย่อยได้ เช่น:

  • src/main.rs — เรียก CLI
  • src/commands/hello.rs — ประมวลผลคำสั่ง hello
  • src/commands/sum.rs — ประมวลผลคำสั่ง sum

🌟 เพิ่มสีสันด้วย colored




[dependencies]

colored = “2”

use colored::*;

fn main() {
    println!("{}", "Hello in Green!".green());
}
  

📦 แจกจ่าย Binary ด้วย cargo install

cargo install --path .
  

📦 ทำให้ CLI ของคุณใช้ได้ในทุกที่

  • Build cross-platform: cargo build --release
  • ใส่ไฟล์ binary ใน PATH หรือแจกจ่ายผ่าน GitHub release
  • หรือใช้ crates.io เผยแพร่ public tool

💡 ตัวอย่าง CLI ที่ใช้ Rust

  • fd — ค้นหาไฟล์เร็วกว่า find
  • ripgrep — ค้นหาข้อความในไฟล์
  • starship — Prompt ที่สวยงามและเร็ว

✅ สรุป

การสร้าง CLI Tool ด้วย Rust ไม่เพียงแต่ได้ performance สูง แต่ยังได้เครื่องมือที่เสถียร ปลอดภัย และ maintain ได้ดีในระยะยาว ลองเริ่มเขียนดู แล้วคุณจะรู้ว่าการสร้าง CLI แบบมืออาชีพไม่ใช่เรื่องยากอีกต่อไป!


บทความนี้ใช้เวลาอ่านประมาณ 20 นาที โดยทีมงาน poolsawat.com

Leave a Reply

อีเมลของคุณจะไม่แสดงให้คนอื่นเห็น ช่องข้อมูลจำเป็นถูกทำเครื่องหมาย *