Rust เป็นภาษา Systems Programming ที่ Stack Overflow Survey จัดให้เป็น "Most Admired Language" 9 ปีซ้อน ด้วยจุดเด่นเรื่อง Memory Safety และ Performance ระดับ C/C++ แต่ไม่ต้องมี Garbage Collector ปี 2026 บริษัทใหญ่ๆ เช่น Microsoft, Google, Meta, Amazon ล้วนใช้ Rust ในการพัฒนา Infrastructure สำคัญ บทความนี้จะสอนพื้นฐาน Rust ตั้งแต่เริ่มต้นจนสามารถเขียนโปรแกรมได้
ทำไมต้องเรียน Rust?
# =============================================
# จุดเด่นของ Rust:
# =============================================
# 1. Memory Safety ไม่มี Null Pointer / Dangling Pointer
# 2. No Garbage Collector - Zero-cost Abstractions
# 3. Performance เทียบเท่า C/C++
# 4. Thread Safety ป้องกัน Data Race
# 5. Pattern Matching ทรงพลัง
# 6. Cargo (Package Manager) ดีที่สุด
# 7. Cross-platform รองรับ Windows/Linux/Mac/WASM
# 8. Community แข็งแรง ปี 2026 มี 300K+ crates
#
# ใครใช้ Rust?
# → Mozilla (Firefox Servo Engine)
# → Microsoft (Windows Kernel, Azure)
# → AWS (Firecracker VMM)
# → Discord (Read States Service)
# → Cloudflare (Pingora, BoringTun)
# → Meta (Source Control, Buck2)
# → Linux Kernel (เริ่มใช้ Rust ตั้งแต่ 2022)
การติดตั้ง Rust
# Install Rust (ทุก OS):
# curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
# หรือ Windows: ไปที่ rustup.rs โหลด rustup-init.exe
#
# ตรวจสอบ:
# rustc --version # Compiler
# cargo --version # Package Manager
#
# Tools ที่มากับ Rust:
# - rustc: Compiler
# - cargo: Build System + Package Manager
# - rustfmt: Code Formatter
# - clippy: Linter
# - rust-analyzer: LSP สำหรับ VSCode/IDE
Hello World และ Cargo
# สร้างโปรเจกต์ใหม่:
# cargo new hello_world
# cd hello_world
#
# โครงสร้างโปรเจกต์:
# hello_world/
# ├── Cargo.toml # Config + Dependencies
# ├── Cargo.lock # Lockfile (เหมือน package-lock.json)
# └── src/
# └── main.rs # Entry point
#
# src/main.rs:
# fn main() {
# println!("Hello, World!");
# }
#
# รัน:
# cargo run # Build + Run
# cargo build # Build เฉยๆ
# cargo build --release # Build แบบ Optimized
# cargo test # รัน Tests
# cargo check # ตรวจ Error โดยไม่ Build
Variables และ Mutability
# Rust Variables เป็น Immutable by default:
# let x = 5; // Immutable
# x = 6; // Error! cannot assign twice
#
# let mut y = 5; // Mutable
# y = 6; // OK
#
# # Constants:
# const MAX_POINTS: u32 = 100_000;
#
# # Shadowing:
# let x = 5;
# let x = x + 1; // New variable x = 6
# let x = x * 2; // New variable x = 12
#
# # Type Inference:
# let a = 5; // i32
# let b = 5.0; // f64
# let c = true; // bool
# let d = "hello"; // &str
# let e = 'A'; // char
Data Types
# Scalar Types:
# i8, i16, i32, i64, i128, isize # Signed integers
# u8, u16, u32, u64, u128, usize # Unsigned
# f32, f64 # Floats
# bool # true/false
# char # Unicode (4 bytes)
#
# Compound Types:
# let tup: (i32, f64, u8) = (500, 6.4, 1);
# let (x, y, z) = tup; # Destructuring
# let five_hundred = tup.0;
#
# Array (fixed size):
# let arr = [1, 2, 3, 4, 5];
# let arr: [i32; 5] = [1, 2, 3, 4, 5];
# let first = arr[0];
#
# Vector (dynamic):
# let mut v: Vec = Vec::new();
# v.push(1);
# v.push(2);
# let v = vec![1, 2, 3];
#
# String vs &str:
# let s: &str = "hello"; # String slice (immutable)
# let s: String = String::from("hello"); # Owned String
Ownership — แนวคิดสำคัญที่สุดของ Rust
# Ownership Rules:
# 1. แต่ละ Value มี Owner เดียว
# 2. เมื่อ Owner หมดขอบเขต Value ถูก Drop
# 3. Value ย้าย Ownership ได้ (Move)
#
# ตัวอย่าง Move:
# let s1 = String::from("hello");
# let s2 = s1; # Move! s1 ใช้ไม่ได้แล้ว
# println!("{}", s1); # Error! value borrowed after move
#
# Clone (Copy ข้อมูล):
# let s1 = String::from("hello");
# let s2 = s1.clone(); # Deep copy
# println!("{} {}", s1, s2); # OK!
#
# References (Borrowing):
# fn calculate_length(s: &String) -> usize {
# s.len()
# }
# let s1 = String::from("hello");
# let len = calculate_length(&s1); # ส่ง Reference
# println!("{} has length {}", s1, len); # s1 ยังใช้ได้!
#
# Mutable References:
# fn change(s: &mut String) {
# s.push_str(", world");
# }
# let mut s = String::from("hello");
# change(&mut s);
#
# Rules ของ References:
# 1. มี 1 Mutable Reference หรือหลาย Immutable Reference
# 2. Reference ต้อง Valid เสมอ
Functions
# Function Basic:
# fn greet(name: &str) -> String {
# format!("Hello, {}!", name)
# }
#
# # Multiple Parameters:
# fn add(x: i32, y: i32) -> i32 {
# x + y # Return implicit (ไม่มี ;)
# // return x + y; -- เขียนแบบนี้ก็ได้
# }
#
# # Expression vs Statement:
# let y = {
# let x = 3;
# x + 1 # Expression (ไม่มี ;)
# };
# // y = 4
#
# # Generic Functions:
# fn largest(list: &[T]) -> &T {
# let mut largest = &list[0];
# for item in list {
# if item > largest {
# largest = item;
# }
# }
# largest
# }
Control Flow
# if/else:
# let number = 6;
# if number % 4 == 0 {
# println!("divisible by 4");
# } else if number % 3 == 0 {
# println!("divisible by 3");
# } else {
# println!("not divisible");
# }
#
# # if ใน let:
# let condition = true;
# let number = if condition { 5 } else { 6 };
#
# # Loops:
# # 1. loop (infinite):
# loop {
# println!("forever");
# break;
# }
#
# # 2. while:
# let mut n = 3;
# while n != 0 {
# println!("{}!", n);
# n -= 1;
# }
#
# # 3. for:
# let a = [10, 20, 30, 40, 50];
# for element in a {
# println!("{}", element);
# }
#
# for number in 1..4 { # 1, 2, 3
# println!("{}!", number);
# }
Structs และ Enums
# Struct:
# struct User {
# username: String,
# email: String,
# active: bool,
# }
#
# let user1 = User {
# username: String::from("somchai"),
# email: String::from("somchai@example.com"),
# active: true,
# };
#
# # Methods (impl block):
# impl User {
# fn new(username: String, email: String) -> Self {
# User { username, email, active: true }
# }
#
# fn deactivate(&mut self) {
# self.active = false;
# }
# }
#
# # Enums:
# enum IpAddr {
# V4(String),
# V6(String),
# }
#
# let home = IpAddr::V4(String::from("127.0.0.1"));
#
# # Pattern Matching:
# match home {
# IpAddr::V4(addr) => println!("IPv4: {}", addr),
# IpAddr::V6(addr) => println!("IPv6: {}", addr),
# }
#
# # Option (แทน null):
# let some_number: Option = Some(5);
# let none_number: Option = None;
#
# match some_number {
# Some(x) => println!("Got {}", x),
# None => println!("No value"),
# }
#
# # if let (Shortcut):
# if let Some(x) = some_number {
# println!("{}", x);
# }
Error Handling
# Result:
# use std::fs::File;
# use std::io::Read;
#
# fn read_file(path: &str) -> Result {
# let mut file = File::open(path)?; # ? ใช้ handle error
# let mut contents = String::new();
# file.read_to_string(&mut contents)?;
# Ok(contents)
# }
#
# # Match Result:
# match read_file("config.toml") {
# Ok(contents) => println!("File: {}", contents),
# Err(e) => println!("Error: {}", e),
# }
#
# # Unwrap (panic if error):
# let x: i32 = "5".parse().unwrap(); # OK: 5
# let y: i32 = "abc".parse().unwrap(); # Panic!
#
# # Expect (with message):
# let x: i32 = "5".parse().expect("Not a number");
#
# # panic! macro:
# if critical_error {
# panic!("critical error occurred!");
# }
Iterators และ Closures
# Iterator Pattern:
# let v = vec![1, 2, 3, 4, 5];
#
# # map:
# let doubled: Vec = v.iter().map(|x| x * 2).collect();
#
# # filter:
# let even: Vec = v.iter().filter(|x| *x % 2 == 0).cloned().collect();
#
# # reduce/fold:
# let sum: i32 = v.iter().sum();
# let product: i32 = v.iter().product();
# let custom: i32 = v.iter().fold(0, |acc, x| acc + x * 2);
#
# # Chaining:
# let result: Vec = v.iter()
# .filter(|x| **x > 2)
# .map(|x| x * 10)
# .collect();
# // [30, 40, 50]
#
# # Closures (Lambda):
# let add_one = |x: i32| -> i32 { x + 1 };
# let y = add_one(5); // 6
#
# # Closure with capture:
# let factor = 3;
# let multiply = |x| x * factor;
# let z = multiply(4); // 12
Cargo — Package Manager
# Cargo.toml:
# [package]
# name = "my_project"
# version = "0.1.0"
# edition = "2021"
#
# [dependencies]
# serde = { version = "1.0", features = ["derive"] }
# tokio = { version = "1", features = ["full"] }
# reqwest = "0.11"
#
# [dev-dependencies]
# mockito = "1.0"
#
# # Commands:
# cargo new my_project # สร้างโปรเจกต์
# cargo add serde # เพิ่ม Dependency
# cargo build # Build
# cargo build --release # Build Optimized
# cargo run # Build + Run
# cargo test # Run Tests
# cargo doc --open # สร้าง Documentation
# cargo fmt # Format Code
# cargo clippy # Linter
# cargo update # อัพเดท Dependencies
# cargo publish # Publish ไป crates.io
Async/Await และ Tokio
# Cargo.toml:
# tokio = { version = "1", features = ["full"] }
#
# # Async Function:
# async fn fetch_url(url: &str) -> Result {
# let response = reqwest::get(url).await?;
# let body = response.text().await?;
# Ok(body)
# }
#
# #[tokio::main]
# async fn main() {
# let body = fetch_url("https://httpbin.org/get").await.unwrap();
# println!("{}", body);
# }
#
# # Multiple Concurrent Requests:
# let urls = vec!["url1", "url2", "url3"];
# let futures: Vec<_> = urls.iter().map(|u| fetch_url(u)).collect();
# let results = futures::future::join_all(futures).await;
Project Example: TCP Echo Server
# Cargo.toml:
# tokio = { version = "1", features = ["full"] }
#
# use tokio::net::TcpListener;
# use tokio::io::{AsyncReadExt, AsyncWriteExt};
#
# #[tokio::main]
# async fn main() -> Result<(), Box> {
# let listener = TcpListener::bind("127.0.0.1:8080").await?;
# println!("Server listening on :8080");
#
# loop {
# let (mut socket, addr) = listener.accept().await?;
# println!("New connection from {}", addr);
#
# tokio::spawn(async move {
# let mut buf = [0; 1024];
# loop {
# let n = socket.read(&mut buf).await.unwrap();
# if n == 0 { break; }
# socket.write_all(&buf[0..n]).await.unwrap();
# }
# });
# }
# }
Rust vs ภาษาอื่น
| Feature | Rust | Go | C++ | Python |
|---|---|---|---|---|
| Memory Safety | Yes (Compile) | Yes (GC) | No | Yes (GC) |
| Performance | Excellent | Good | Excellent | Slow |
| Learning Curve | Steep | Easy | Hard | Easy |
| Concurrency | async/await | Goroutines | std::thread | asyncio |
| Compile Time | Slow | Fast | Slow | N/A |
| Use Cases | Systems, CLI, WASM | Backend, DevOps | Systems, Games | AI, Scripts |
สรุป: Rust ปี 2026
Rust เป็นภาษาที่น่าเรียนในปี 2026 ด้วย Memory Safety ระดับ Compile-time และ Performance ที่ยอดเยี่ยม เริ่มจาก Ownership ให้เข้าใจแล้วจึงต่อยอดไป Pattern Matching และ Async/Await การเรียน Rust อาจใช้เวลา 2-3 เดือนแต่คุ้มค่ากับการได้เข้าใจ Systems Programming อย่างลึกซึ้ง
