แบบฝึกหัด: บทที่ 2 - Variables & Data Types
แบบฝึกหัดที่ 1: Mutability
แก้ไขโค้ดนี้ให้ทำงานได้:
fn main() {
let x = 5;
x = 10;
println!("{}", x);
}
ดูเฉลย
fn main() {
let mut x = 5; // เพิ่ม mut
x = 10;
println!("{}", x);
}
แบบฝึกหัดที่ 2: Type Annotation
เติม type ให้ถูกต้อง:
fn main() {
let a: ____ = 42;
let b: ____ = 3.14;
let c: ____ = true;
let d: ____ = 'A';
let e: ____ = "Hello";
}
ดูเฉลย
fn main() {
let a: i32 = 42;
let b: f64 = 3.14;
let c: bool = true;
let d: char = 'A';
let e: &str = "Hello";
}
แบบฝึกหัดที่ 3: Shadowing
ผลลัพธ์ของโค้ดนี้คืออะไร?
fn main() {
let x = 5;
let x = x + 1;
{
let x = x * 2;
println!("inner: {}", x);
}
println!("outer: {}", x);
}
ดูเฉลย
inner: 12
outer: 6
อธิบาย:
x = 5x = 5 + 1 = 6(shadowing)- ใน block:
x = 6 * 2 = 12(shadowing เฉพาะใน block) - เมื่อออกจาก block:
xกลับมาเป็น 6
แบบฝึกหัดที่ 4: Tuple และ Array
สร้างโค้ดที่:
- สร้าง tuple
(i32, f64, bool)ค่า(10, 3.14, true) - Destructure ออกมาเป็น 3 ตัวแปร
- สร้าง array ของ i32 ขนาด 5 ค่า [1, 2, 3, 4, 5]
- Print ค่าแรกและค่าสุดท้าย
ดูเฉลย
fn main() {
// Tuple
let tup: (i32, f64, bool) = (10, 3.14, true);
let (a, b, c) = tup;
println!("a={}, b={}, c={}", a, b, c);
// Array
let arr: [i32; 5] = [1, 2, 3, 4, 5];
println!("first: {}, last: {}", arr[0], arr[4]);
}
แบบฝึกหัดที่ 5: Constants
ประกาศ constant ที่:
- ชื่อ
MAX_USERS - Type
u32 - ค่า 1000
ดูเฉลย
const MAX_USERS: u32 = 1000;
fn main() {
println!("Max users: {}", MAX_USERS);
}
หมายเหตุ:
constต้องระบุ type เสมอ- ใช้ SCREAMING_SNAKE_CASE
- ต้องกำหนดค่าตอน compile time
👉 บทที่ 3