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

Mutability - ความสามารถในการเปลี่ยนแปลงค่า

ประกาศตัวแปรด้วย let

ใน Rust เราใช้ let เพื่อประกาศตัวแปร:

fn main() {
    let x = 5;
    println!("x = {}", x);
}

ผลลัพธ์:

x = 5

ตัวแปรเปลี่ยนค่าไม่ได้ (Immutable)

ตัวแปรใน Rust เปลี่ยนค่าไม่ได้โดยปกติ!

fn main() {
    let x = 5;
    println!("x = {}", x);
    x = 6; // ❌ Error!
}

Error:

error[E0384]: cannot assign twice to immutable variable `x`

ทำไมถึงเป็นแบบนี้?

เพราะ immutable ทำให้โค้ดปลอดภัยและคาดเดาได้ง่ายกว่า เมื่อค่าไม่เปลี่ยน เราไม่ต้องกังวลว่าจะมีโค้ดส่วนอื่นแก้ไขค่าโดยไม่รู้ตัว


ตัวแปรเปลี่ยนค่าได้ (Mutable)

ถ้าต้องการเปลี่ยนค่า ให้เพิ่ม mut:

fn main() {
    let mut x = 5;
    println!("x = {}", x);

    x = 6; // ✅ OK เพราะใช้ mut
    println!("x = {}", x);
}

ผลลัพธ์:

x = 5
x = 6

เมื่อไหร่ควรใช้ mut?

✅ ใช้ mut เมื่อ:

  • ต้องการสะสมค่า (เช่น ตัวนับ, ผลรวม)
  • ต้องการแก้ไขข้อมูลใน loop
fn main() {
    let mut sum = 0;

    sum = sum + 1;
    sum = sum + 2;
    sum = sum + 3;

    println!("sum = {}", sum); // 6
}

❌ ไม่ต้องใช้ mut เมื่อ:

  • ค่าไม่เปลี่ยนแปลง
  • ต้องการความปลอดภัย
fn main() {
    let name = "Rust";
    let pi = 3.14159;

    println!("Learning {} with pi = {}", name, pi);
}

Shadowing (การซ่อนตัวแปร)

Rust อนุญาตให้ประกาศตัวแปรชื่อเดิมซ้ำได้:

fn main() {
    let x = 5;
    println!("x = {}", x); // 5

    let x = x + 1; // สร้างตัวแปรใหม่ชื่อ x
    println!("x = {}", x); // 6

    let x = x * 2;
    println!("x = {}", x); // 12
}

Shadowing vs mut

Shadowingmut
สร้างตัวแปรใหม่แก้ไขตัวแปรเดิม
เปลี่ยนชนิดได้เปลี่ยนชนิดไม่ได้
ใช้ let ซ้ำไม่ต้องใช้ let
fn main() {
    // Shadowing - เปลี่ยนชนิดได้
    let spaces = "   ";      // &str (string)
    let spaces = spaces.len(); // usize (number)
    println!("spaces = {}", spaces); // 3

    // mut - เปลี่ยนชนิดไม่ได้
    // let mut spaces = "   ";
    // spaces = spaces.len(); // ❌ Error! ชนิดต่างกัน
}

ลองทำดู! 🎯

  1. ประกาศตัวแปร age และพยายามเปลี่ยนค่า ดูว่า error อะไร
  2. เพิ่ม mut แล้วลองอีกครั้ง
  3. ลอง shadowing: ประกาศ let x = 5; แล้วตามด้วย let x = "hello";

สรุป

แนวคิดคำอธิบาย
let x = 5;ตัวแปร immutable
let mut x = 5;ตัวแปร mutable
Shadowingประกาศตัวแปรชื่อเดิมซ้ำ

👉 ต่อไป: ชนิดข้อมูล