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

แบบฝึกหัด: บทที่ 1 - Getting Started

แบบฝึกหัดที่ 1: ติดตั้งและตรวจสอบ

ติดตั้ง Rust และตรวจสอบว่าติดตั้งสำเร็จ

คำถาม: คำสั่งอะไรใช้ตรวจสอบเวอร์ชัน Rust?

ดูเฉลย
rustc --version
cargo --version

แบบฝึกหัดที่ 2: Hello World

สร้างโปรเจกต์ใหม่และแก้ไขให้แสดง “สวัสดี Rust!”

ขั้นตอน:

  1. สร้างโปรเจกต์ใหม่ชื่อ hello_thai
  2. แก้ไข main.rs ให้แสดง “สวัสดี Rust!”
  3. รันโปรแกรม
ดูเฉลย
cargo new hello_thai
cd hello_thai
// src/main.rs
fn main() {
    println!("สวัสดี Rust!");
}
cargo run

แบบฝึกหัดที่ 3: Cargo คำสั่งพื้นฐาน

เติมคำสั่ง Cargo ให้ถูกต้อง:

  1. สร้างโปรเจกต์ใหม่: cargo ______ my_project
  2. Build โปรเจกต์: cargo ______
  3. รันโปรเจกต์: cargo ______
  4. Check โค้ด (ไม่ build): cargo ______
ดูเฉลย
  1. cargo new my_project
  2. cargo build
  3. cargo run
  4. cargo check

แบบฝึกหัดที่ 4: โครงสร้างโปรเจกต์

หลังจากรัน cargo new my_project จะได้โครงสร้างแบบไหน?

ดูเฉลย
my_project/
├── Cargo.toml
└── src/
    └── main.rs
  • Cargo.toml - ไฟล์ config ของโปรเจกต์
  • src/main.rs - ไฟล์โค้ดหลัก

แบบฝึกหัดที่ 5: แก้ไข Cargo.toml

เพิ่ม dependency rand เวอร์ชัน 0.8 ใน Cargo.toml

ดูเฉลย
[package]
name = "my_project"
version = "0.1.0"
edition = "2024"

[dependencies]
rand = "0.8"

หรือใช้คำสั่ง:

cargo add rand

👉 บทที่ 2