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 build | Compile โปรเจกต์ |
cargo run | Compile และ run |
cargo check | ตรวจสอบโค้ด |
cargo build --release | Build สำหรับ production |
ลองทำดู! 🎯
- สร้างโปรเจกต์ใหม่ชื่อ
my_project - แก้ไข
main.rsให้พิมพ์ข้อความอื่น - รันด้วย
cargo run - ลอง
cargo checkดู
สรุปบทที่ 1
ในบทนี้คุณได้เรียนรู้:
- ✅ ติดตั้ง Rust ด้วย rustup
- ✅ เขียนโปรแกรม Hello World
- ✅ ใช้งาน Cargo เบื้องต้น
👉 ต่อไป: บทที่ 2: Variables & Data Types