Functions
การประกาศฟังก์ชัน
หัวข้อที่มีชื่อว่า “การประกาศฟังก์ชัน”ใช้ fn ในการประกาศฟังก์ชัน ทุก parameter ต้องมี type annotation อย่างชัดเจน — คอมไพเลอร์ไม่อนุมาน type ของ parameter return type เขียนตามหลัง ->
fn add(a: i32, b: i32) -> i32 { a + b}ฟังก์ชันสามารถประกาศก่อนหรือหลังที่ถูกเรียกใช้ — Rust ไม่ต้องการ forward declaration
Statements vs Expressions
หัวข้อที่มีชื่อว่า “Statements vs Expressions”นี่คือความแตกต่างที่สำคัญที่สุดใน function body ของ Rust:
- Statement ทำและ ไม่ ผลิตค่า
let x = 5;คือ statement ที่ลงท้ายด้วย semicolon - Expression ประเมินเป็นค่า
5 + 3คือ expression block{ ... }ก็เป็น expression เช่นกัน
fn main() { // นี่คือ statement — ไม่ผลิตค่า let y = 6;
// นี่คือ expression block — ผลิตค่า 12 let z = { let x = 3; x * 4 // ไม่มี semicolon — นี่คือค่าของ block };
println!("y={}, z={}", y, z);}การเพิ่ม semicolon ที่บรรทัดสุดท้ายของ block จะ แปลง expression เป็น statement — block จะ return unit type () แทนที่จะเป็นค่าที่คำนวณได้
Trailing-Expression Return
หัวข้อที่มีชื่อว่า “Trailing-Expression Return”expression สุดท้ายใน function body ที่เขียน โดยไม่มี semicolon คือ return value คุณยังสามารถใช้ keyword return สำหรับ early return ได้ แต่ Rust ที่เป็น idiomatic นิยม trailing expression สำหรับ return path หลัก
fn square(n: i32) -> i32 { n * n // return เพราะไม่มี semicolon}
fn max_of_two(a: i32, b: i32) -> i32 { if a > b { a } else { b } // if เป็น expression}Unit Type
หัวข้อที่มีชื่อว่า “Unit Type”ฟังก์ชันที่ไม่ return ค่าที่มีความหมาย จะ return () (unit type) โดยอัตโนมัติ signature fn foo() เป็น shorthand ของ fn foo() -> () unit type คล้าย void ในภาษาอื่น แต่เป็น type จริงๆ ที่มีค่าเดียว: ()
fn greet(name: &str) { // return () โดยอัตโนมัติ println!("Hello, {}!", name);}fn add(a: i32, b: i32) -> i32 { a + b // trailing expression -- no semicolon -- is the return value}
fn describe(n: i32) -> &'static str { if n > 0 { "positive" } else if n < 0 { "negative" } else { "zero" }}
fn unit_example() { // Functions without -> return the unit type () println!("unit example");}
fn main() { let sum = add(3, 4); println!("add(3, 4) = {}", sum);
println!("describe(10) = {}", describe(10)); println!("describe(-3) = {}", describe(-3)); println!("describe(0) = {}", describe(0));
unit_example();}Compiling…