Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

การสร้างฟังก์ชัน

Syntax พื้นฐาน

fn function_name() {
    // body
}

📐 Function Anatomy

+-------------------------------------------------------------------+
|                  Function Anatomy in Rust                         |
+-------------------------------------------------------------------+
|                                                                   |
|   fn   calculate_sum  (  a: i32  ,  b: i32  )  ->  i32   {        |
|   ^         ^            ^--^       ^--^        ^--^      ^       |
|   |         |            |  |       |  |        |  |      |       |
|   |         |            |  type    |  type     |  return |       |
|   |         |            param      param       |  type   body    |
|   |         function name                       return            |
|   keyword                                                         |
|                                                                   |
|       a + b    <--- Expression (no semicolon) = return value      |
|   }                                                               |
|                                                                   |
+-------------------------------------------------------------------+
|   Tip: No semicolon after expression = return that value          |
+-------------------------------------------------------------------+

ตัวอย่าง

fn main() {
    println!("Hello from main!");

    another_function();
}

fn another_function() {
    println!("Hello from another function!");
}

ผลลัพธ์:

Hello from main!
Hello from another function!

Naming Conventions

ใน Rust ใช้ snake_case สำหรับชื่อฟังก์ชัน:

#![allow(unused)]
fn main() {
// ✅ ถูกต้อง - snake_case
fn calculate_area() {}
fn get_user_name() {}
fn process_data() {}

// ❌ ไม่ใช่ convention ของ Rust
fn CalculateArea() {} // PascalCase
fn calculateArea() {} // camelCase
}

ตำแหน่งของฟังก์ชัน

ฟังก์ชันสามารถประกาศไว้ที่ไหนก็ได้ในไฟล์:

fn main() {
    greet(); // เรียกฟังก์ชันที่อยู่ข้างล่าง ✅
}

fn greet() {
    println!("Hello!");
}

หมายเหตุ: ต่างจากบางภาษา (เช่น C) ที่ต้องประกาศฟังก์ชันก่อนเรียกใช้ Rust ไม่สนใจลำดับการประกาศ


ฟังก์ชันซ้อนกัน (ไม่ได้!)

ใน Rust ไม่สามารถประกาศฟังก์ชันซ้อนในฟังก์ชันได้:

// ❌ ไม่ได้
fn outer() {
    fn inner() { // Error!
        println!("Inner");
    }
    inner();
}

เคล็ดลับ: ถ้าต้องการ nested function ใช้ closure แทน:

fn main() {
    // ✅ ใช้ closure แทน nested function
    let greet = |name: &str| {
        println!("Hello, {}!", name);
    };

    greet("Rust");
    greet("World");

    // closure ที่จับตัวแปรจากภายนอก
    let multiplier = 3;
    let multiply = |x: i32| x * multiplier;

    println!("5 * 3 = {}", multiply(5)); // 15
}

ตัวอย่างจริง

fn main() {
    print_welcome_message();
    print_separator();
    print_goodbye_message();
}

fn print_welcome_message() {
    println!("╔═══════════════════════╗");
    println!("║   Welcome to Rust!    ║");
    println!("╚═══════════════════════╝");
}

fn print_separator() {
    println!("─────────────────────────");
}

fn print_goodbye_message() {
    println!("Thanks for learning Rust!");
}

ลองทำดู! 🎯

  1. สร้างฟังก์ชัน print_name ที่พิมพ์ชื่อของคุณ
  2. สร้างฟังก์ชัน print_age ที่พิมพ์อายุ
  3. เรียกใช้ทั้งสองฟังก์ชันจาก main

สรุป

แนวคิดคำอธิบาย
fn name() {}ประกาศฟังก์ชัน
snake_caseNaming convention
ลำดับไม่สำคัญประกาศที่ไหนก็ได้

👉 ต่อไป: Parameters