Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Cargo เบื้องต้น

Cargo เป็นเครื่องมือจัดการโปรเจกต์และ package manager ของ Rust มาพร้อมกับ rustup

Cargo ทำอะไรได้บ้าง?

  • 📦 สร้างโปรเจกต์ใหม่
  • 🔨 Build โค้ด
  • ▶️ รันโปรแกรม
  • 📥 จัดการ dependencies (libraries ที่ใช้)
  • 🧪 รัน tests
  • 📖 สร้าง documentation

สร้างโปรเจกต์ใหม่

cargo new hello_cargo
cd hello_cargo

Cargo จะสร้างโครงสร้างโฟลเดอร์ให้:

hello_cargo/
+-- Cargo.toml
\-- src/
    \-- main.rs

ทำความเข้าใจโครงสร้าง

Cargo.toml

[package]
name = "hello_cargo"
version = "0.1.0"
edition = "2024"

[dependencies]
  • [package] - ข้อมูลโปรเจกต์
    • name - ชื่อโปรเจกต์
    • version - เวอร์ชัน
    • edition - Rust edition (ปกติใช้ปีล่าสุด)
  • [dependencies] - รายการ libraries ที่ใช้

src/main.rs

fn main() {
    println!("Hello, world!");
}

โค้ดเริ่มต้นที่ Cargo สร้างให้


คำสั่ง Cargo ที่ใช้บ่อย

Build โปรเจกต์

cargo build

จะสร้างไฟล์ executable ใน target/debug/:

target/debug/hello_cargo

Build แบบ Release (เร็วกว่า)

cargo build --release

ไฟล์จะอยู่ใน target/release/ - เหมาะสำหรับ production

รันโปรแกรม

cargo run

คำสั่งนี้จะ build และ run ในคำสั่งเดียว สะดวกมาก!

   Compiling hello_cargo v0.1.0
    Finished dev [unoptimized + debuginfo] target(s) in 0.50s
     Running target/debug/hello_cargo
Hello, world!

ตรวจสอบโค้ด (ไม่ build)

cargo check

เร็วกว่า cargo build เพราะไม่สร้างไฟล์ executable ใช้ตรวจสอบว่าโค้ด compile ได้หรือไม่


เพิ่ม Dependencies

เมื่อต้องการใช้ library ภายนอก ให้เพิ่มใน Cargo.toml:

[dependencies]
rand = "0.8"

จากนั้นรัน:

cargo build

Cargo จะดาวน์โหลด library ให้อัตโนมัติ

หมายเหตุ: Library ของ Rust เรียกว่า crate หา crates ได้ที่ crates.io


สรุปคำสั่ง Cargo

คำสั่งหน้าที่
cargo new <name>สร้างโปรเจกต์ใหม่
cargo buildCompile โปรเจกต์
cargo runCompile และ run
cargo checkตรวจสอบโค้ด
cargo build --releaseBuild สำหรับ production

ลองทำดู! 🎯

  1. สร้างโปรเจกต์ใหม่ชื่อ my_project
  2. แก้ไข main.rs ให้พิมพ์ข้อความอื่น
  3. รันด้วย cargo run
  4. ลอง cargo check ดู

สรุปบทที่ 1

ในบทนี้คุณได้เรียนรู้:

  • ✅ ติดตั้ง Rust ด้วย rustup
  • ✅ เขียนโปรแกรม Hello World
  • ✅ ใช้งาน Cargo เบื้องต้น

👉 ต่อไป: บทที่ 2: Variables & Data Types