พื้นฐาน Rust

Rust Variables, mut, const and Shadowing

Variables in Rust cannot change unless you ask. Learn let, let mut, const and shadowing.

  • ระดับเริ่มต้น
  • อ่าน 2 นาที
  • ตัวอย่างที่รันได้ 1 ตัวอย่าง
สิ่งที่คุณจะได้เรียนรู้
  • let and let mut
  • Constants with const
  • Shadowing a variable
Declaration → what it allows
let language = "Rust"cannot change
let mut score = 10can change
const MAX_SCORE: u32 = 100fixed for the whole program
let score = score * 2 → a new variable, 30

Immutable by default

Variables in Rust cannot change unless you say so. let creates a variable, let mut creates one you can change, and const creates a value that is fixed for the whole program.

score is declared with mut, so score += 5 is allowed. The second let score creates a new variable with the same name, which is called shadowing. The braces in println! print the variables named inside them.

ประเด็นสำคัญ

  1. let creates a variable that cannot change.
  2. let mut allows the value to change.
  3. A second let with the same name creates a new variable (shadowing).

ตัวอย่าง Rust ที่รันได้

Rust
รันโค้ด →
main.rs
fn main() {
    let language = "Rust";
    let mut score = 10;
    score += 5;

    const MAX_SCORE: u32 = 100;
    let score = score * 2; // shadowing creates a new variable

    println!("{language}: {score} of {MAX_SCORE}");
}
สร้างปุ่ม Run สำหรับตัวอย่างนี้ ผลลัพธ์จากการรันโค้ด
Rust: 30 of 100

ฝึกฝน

เปิดตัวอย่างในคอมไพเลอร์ออนไลน์ ลองเปลี่ยนค่าหรือเพิ่มบรรทัด แล้วทายผลลัพธ์ก่อนกดรัน จากนั้นลองทำให้โค้ดผิดโดยตั้งใจ แล้วอ่านข้อความจากคอมไพเลอร์

เรียนบทนี้จบแล้วใช่ไหม

ทำเครื่องหมายว่าเรียนแล้วเพื่อติดตามความคืบหน้า

ถัดไป: Data Types →

ฝึกด้วยโจทย์

ใช้สิ่งที่เรียนในบทนี้แก้ปัญหาจริง ทุกโจทย์รันในเบราว์เซอร์ พร้อมการทดสอบทันทีและรีวิวจาก AI

โจทย์ทั้งหมด