ข้ามไปยังเนื้อหา

พื้นฐาน & ไวยากรณ์

Rust คือ ภาษาโปรแกรมระดับระบบ (systems programming language) ที่ออกแบบมาเพื่อเป้าหมายสามประการ:

  1. ความปลอดภัยของหน่วยความจำ — คอมไพเลอร์รับประกันความปลอดภัยจาก null-pointer dereference, use-after-free bug และ data race ทั้งหมดนี้ทำที่ compile time
  2. ประสิทธิภาพ — Rust คอมไพล์เป็น machine code โดยตรงโดยไม่มี runtime overhead ไม่มี garbage collector ไม่มี virtual machine ไม่มี interpreter
  3. Concurrency ที่ไม่น่ากลัว — กฎ ownership เดียวกันที่ป้องกัน memory bug ยังป้องกัน data race ระหว่าง thread อีกด้วย

แนวคิดสำคัญคือ Rust บรรลุการรับประกันเหล่านี้ผ่าน borrow checker ที่เป็นส่วนหนึ่งของคอมไพเลอร์ที่บังคับใช้กฎ ownership และ lifetime ก่อนที่โปรแกรมจะรันจริง หากคอมไพล์ผ่าน แสดงว่าโปรแกรมปลอดภัยในด้านหน่วยความจำ

บทเรียนแนวคิด
Variables & Mutabilitylet, mut, shadowing, const
Data TypesScalar, tuple, array, type inference
Functionsfn, parameters, return types, expressions vs statements
Control Flowif แบบ expression, loop, while, for, ranges

ทุก 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);
}
Rust รับประกัน memory safety อย่างไร?
Entry point ของ Rust binary คืออะไร?
placeholder {} ใน println! format string ทำหน้าที่อะไร?