Quiz: บทที่ 2 - Variables & Data Types
คำถามที่ 1
ตัวแปรใน Rust เป็น mutable หรือ immutable โดย default?
A. Mutable
B. Immutable
C. ขึ้นอยู่กับ type
D. ขึ้นอยู่กับ scope
ดูเฉลย
B. Immutable
ต้องใช้ mut เพื่อทำให้เป็น mutable:
let mut x = 5;
คำถามที่ 2
type ใดเป็น default สำหรับ integer?
A. i8
B. i16
C. i32
D. i64
ดูเฉลย
C. i32
let x = 42; // i32 by default
คำถามที่ 3
Shadowing คืออะไร?
A. การลบตัวแปร
B. การประกาศตัวแปรชื่อเดียวกันใหม่
C. การเปลี่ยน type ของตัวแปร
D. การสร้าง reference
ดูเฉลย
B. การประกาศตัวแปรชื่อเดียวกันใหม่
let x = 5;
let x = x + 1; // shadow
คำถามที่ 4
const ต่างจาก let อย่างไร?
A. const เปลี่ยนค่าได้
B. const ต้องระบุ type
C. const ใช้ใน function เท่านั้น
D. ไม่มีความแตกต่าง
ดูเฉลย
B. const ต้องระบุ type
const MAX: u32 = 100; // ต้องระบุ type
let x = 100; // type inference ได้
คำถามที่ 5
ผลลัพธ์ของ code นี้คืออะไร?
let x = 5;
let x = x + 1;
{
let x = x * 2;
}
println!("{}", x);
A. 5
B. 6
C. 12
D. Error
ดูเฉลย
B. 6
x = 5x = 5 + 1 = 6(shadow)- ใน block:
x = 12(shadow เฉพาะ block) - หลัง block:
xกลับมาเป็น 6