พื้นฐาน & ไวยากรณ์
ทำไมต้อง Rust?
หัวข้อที่มีชื่อว่า “ทำไมต้อง Rust?”Rust คือ ภาษาโปรแกรมระดับระบบ (systems programming language) ที่ออกแบบมาเพื่อเป้าหมายสามประการ:
- ความปลอดภัยของหน่วยความจำ — คอมไพเลอร์รับประกันความปลอดภัยจาก null-pointer dereference, use-after-free bug และ data race ทั้งหมดนี้ทำที่ compile time
- ประสิทธิภาพ — Rust คอมไพล์เป็น machine code โดยตรงโดยไม่มี runtime overhead ไม่มี garbage collector ไม่มี virtual machine ไม่มี interpreter
- Concurrency ที่ไม่น่ากลัว — กฎ ownership เดียวกันที่ป้องกัน memory bug ยังป้องกัน data race ระหว่าง thread อีกด้วย
แนวคิดสำคัญคือ Rust บรรลุการรับประกันเหล่านี้ผ่าน borrow checker ที่เป็นส่วนหนึ่งของคอมไพเลอร์ที่บังคับใช้กฎ ownership และ lifetime ก่อนที่โปรแกรมจะรันจริง หากคอมไพล์ผ่าน แสดงว่าโปรแกรมปลอดภัยในด้านหน่วยความจำ
สิ่งที่โมดูลนี้ครอบคลุม
หัวข้อที่มีชื่อว่า “สิ่งที่โมดูลนี้ครอบคลุม”| บทเรียน | แนวคิด |
|---|---|
| Variables & Mutability | let, mut, shadowing, const |
| Data Types | Scalar, tuple, array, type inference |
| Functions | fn, parameters, return types, expressions vs statements |
| Control Flow | if แบบ expression, loop, while, for, ranges |
โปรแกรม Rust แรกของคุณ
หัวข้อที่มีชื่อว่า “โปรแกรม Rust แรกของคุณ”ทุก Rust binary เริ่มต้นจาก fn main() macro println! ใช้เขียนข้อความที่จัดรูปแบบแล้วออก standard output คอมไพเลอร์อนุมาน type เมื่อไม่คลุมเครือ จึงไม่จำเป็นต้องระบุ type ทุกตัวแปร
fn main() { println!("Rust guarantees memory safety at compile time."); println!("No garbage collector. No null pointer exceptions."); println!("Zero-cost abstractions. Systems-level performance.");
let x: i32 = 42; let name = "Rust"; println!("x = {}, name = {}", x, name);}{} ใน format string คือ ตัวแทน (placeholder) — macro จะแทนที่ด้วยค่าของ argument ที่สอดคล้องกันขณะ runtime
fn main() { println!("Rust guarantees memory safety at compile time."); println!("No garbage collector. No null pointer exceptions."); println!("Zero-cost abstractions. Systems-level performance.");
let x: i32 = 42; let name = "Rust"; println!("x = {}, name = {}", x, name);}Compiling…