เขียนโปรแกรม CLI ง่าย ๆ ด้วย Rust

Sharing is caring!

Rust ไม่ได้มีดีแค่ระบบ memory safety และ performance เท่านั้น แต่ยังเหมาะอย่างยิ่งสำหรับการสร้างเครื่องมือ command-line หรือที่เรียกว่า CLI (Command Line Interface) ที่เร็ว ปลอดภัย และใช้งานง่าย

1. เริ่มต้นโปรเจกต์ CLI ด้วย Cargo

cargo new mycli
cd mycli
cargo run

2. รับ argument จากบรรทัดคำสั่ง

Rust มี module std::env สำหรับรับ argument ได้ง่าย

use std::env;

fn main() {
    let args: Vec = env::args().collect();
    if args.len() > 1 {
        println!("Argument แรกคือ: {}", args[1]);
    } else {
        println!("ไม่มี argument ส่งมา");
    }
}

3. ใช้ crate clap เพื่อ parse argument

clap คือ library ยอดนิยมสำหรับทำ CLI

[dependencies]
clap = { version = "4.0", features = ["derive"] }
use clap::Parser;

#[derive(Parser)]
struct Cli {
    #[arg(short, long)]
    name: String,
}

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

4. การสร้างคำสั่งย่อย (Subcommand)

use clap::{Parser, Subcommand};

#[derive(Parser)]
struct Cli {
    #[command(subcommand)]
    command: Commands,
}

#[derive(Subcommand)]
enum Commands {
    Add { a: i32, b: i32 },
    Sub { a: i32, b: i32 },
}

fn main() {
    let cli = Cli::parse();
    match cli.command {
        Commands::Add { a, b } => println!("ผลบวก: {}", a + b),
        Commands::Sub { a, b } => println!("ผลลบ: {}", a - b),
    }
}

5. ตัวอย่าง CLI: เครื่องคิดเลข

เพิ่ม CLI ที่คำนวณค่าจาก input ของผู้ใช้

use std::io;

fn main() {
    println!("กรุณาใส่เลขแรก:");
    let mut input1 = String::new();
    io::stdin().read_line(&mut input1).unwrap();
    let num1: f64 = input1.trim().parse().unwrap();

    println!("ใส่เลขที่สอง:");
    let mut input2 = String::new();
    io::stdin().read_line(&mut input2).unwrap();
    let num2: f64 = input2.trim().parse().unwrap();

    println!("ผลรวม: {}", num1 + num2);
}

6. การจัดการ Error ด้วย Result

fn divide(a: f64, b: f64) -> Result {
    if b == 0.0 {
        Err(String::from("หารด้วยศูนย์ไม่ได้"))
    } else {
        Ok(a / b)
    }
}

7. Distribution CLI Tool เป็น Binary

cargo build --release

จะได้ไฟล์ใน target/release/mycli ที่สามารถ copy ไปใช้บนเครื่องอื่นได้ทันที

8. ตัวอย่าง CLI ชื่อดังที่เขียนด้วย Rust

  • fd – ตัวค้นหาไฟล์เร็วกว่า find
  • bat – cat พร้อม highlight
  • ripgrep – ค้นหาข้อความเร็วสุด
  • starship – prompt terminal แบบ custom

9. ใช้ Structopt (ทางเลือกของ clap)

structopt เคยนิยมมาก ปัจจุบันถูก merge เข้ากับ clap แล้ว

10. แหล่งเรียนรู้ CLI เพิ่มเติม

สรุป

การเขียน CLI ด้วย Rust ง่ายกว่าที่คิด และให้คุณได้โปรแกรมที่เร็ว ปลอดภัย และ maintainable เหมาะทั้งมือใหม่และโปรเจกต์ระดับโปรดักชัน


📌 คำค้น SEO

rust cli, เขียนโปรแกรม command line rust, rust clap crate, รับ argument rust, rust io stdin, rust build binary cli, สร้างโปรแกรมเทอร์มินัล rust, rust calculator cli, rust cli ภาษาไทย

เผยแพร่โดย poolsawat.com

Leave a Reply

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