เรียน Rust ผ่าน Rustlings วันที่ 2
สวัสดีครับ วันนี้เป็นบันทึกการเรียน Rust ผ่านการฝึกด้วย Rustlings วันที่ 2 นะครับ วันนี้นั่งฝึกทบทวน (รอบที่ เท่าไหร่แล้วจำไม่ได้ ไม่ได้ใช้จริงๆจังๆ ก็ลืมหมด)
วิธีการเรียนของผมคือ
- แก้โจทย์ข้อนั้นให้ผ่าน
- อ่าน Hint เช่น
rustlings hint xxx
- ย้อนกลับไปอ่าน Error Code Index ตอน compile ไม่ผ่าน (หรือ
rustc --explain <NUMBER>
)

Exercises ของ Rustlings วันนี้คือ
- variables - จะตรงกับใน Rust Book เรื่อง Variables and Mutability
- function - อ่านเรื่อง How Functions Work
- if - อ่านเรื่อง Control Flow - if expressions
- Quiz 1 - เอาที่เรียนมา ทำ Quiz (ไม่ยาก แค่ If/else)
สรุปจาก Rustlings แต่ละ Exercises และการอ่านเพิ่มเติมจาก Rust Book
Variables
- ตัวแปรโดย default จะเป็น immutable
- ถ้าอยากให้มันแก้ไขได้ ให้ใส่
mut
let mut x = 5;
x = 10;
- ต้อง declare และ initial ก่อนเรียกใช้ตัวแปร
- Constant จะเปลี่ยนค่าไม่ได้ (ใช้
mut
ไม่ได้) always immutable - Constant ต้องกำหนด type ด้วย
- Naming convention ของ constant คือ Uppercase + underscore
const THREE_HOURS_IN_SECONDS: u32 = 60 * 60 * 3;
- shadowing คือการ declare variable ใหม่ ด้วยชื่อเดิม (first variable is shadowed by the second)
- shadowing กับ mut ต่างกันตรงที่ shadowing สามารถเปลี่ยน type ได้
Functions
- function body มี 2 แบบ statement และ expressions
- statement คือทำ action บางอย่าง และไม่มี return value
- expressions คือการ return value (ไม่มี semicolon ที่ตัวสุดท้าย)
- function ที่มี return value จะใช้
->
fn five() -> i32 {
5
}
()
คือ unit type หรือ void หรือไม่มี return value
If
- If condition ต้องเป็น
bool
- ใช้ keyword
if
,else if
และelse
- ไม่ต้องมีวงเล็บใน condition
if fizzish == "fizz" {
"foo"
} else if fizzish == "fuzz" {
"bar"
} else {
"baz"
}
Quiz 1
โจทย์ไม่ยาก ถ้าเคยเขียนโปรแกรมมาก่อนน่าจะทำได้อยู่แล้ว เรียนโปรแกรมมิ่ง หรือ If / Else คาบแรกก็ทำได้ละมั้ง
เขียน function calculate_price_of_apples
โดย apple ราคาลูกละ 2 rustbucks แต่ถ้าซื้อมากกว่า 40 ลูก จะคิดลูกละ 1 rustbucks
จบวันที่ 2 🎉
Happy coding ❤️