Skip to content

Functions (ฟังก์ชัน)

Functions are blocks of code designed to perform specific tasks and can be reused.

Declaring and Calling Functions (การประกาศและเรียกใช้ฟังก์ชัน)

js
// Basic function in JavaScript
// ฟังก์ชันพื้นฐานใน JavaScript
function greet(name) {
  return `Hello ${name}`;
}

// Call the function
// เรียกใช้ฟังก์ชัน
console.log(greet("John")); // "Hello John"

// Arrow function
// Arrow function
const add = (a, b) => a + b;
console.log(add(2, 3)); // 5
rust
// Function in Rust
// ฟังก์ชันใน Rust
fn greet(name: &str) -> String {
    format!("Hello {}", name)
}

fn main() {
    println!("{}", greet("John")); // "Hello John"
    
    // Closure
    // Closure
    let add = |a: i32, b: i32| a + b;
    println!("{}", add(2, 3)); // 5
}
python
# Function in Python
# ฟังก์ชันใน Python
def greet(name):
    return f"Hello {name}"

# Call the function
# เรียกใช้ฟังก์ชัน
print(greet("John"))  # "Hello John"

# Lambda function
# Lambda function
add = lambda a, b: a + b
print(add(2, 3))  # 5
go
// Function in Go
// ฟังก์ชันใน Go
package main

import "fmt"

func greet(name string) string {
    return fmt.Sprintf("Hello %s", name)
}

func add(a, b int) int {
    return a + b
}

func main() {
    fmt.Println(greet("John")) // "Hello John"
    fmt.Println(add(2, 3))     // 5
}

Parameters and Return Values (พารามิเตอร์และค่าที่ส่งคืน)

js
// Function with various parameter types in JavaScript
// ฟังก์ชันที่รับพารามิเตอร์หลายรูปแบบใน JavaScript
function createUser(
  name,
  age = 18, // Default parameter
  ...hobbies // Rest parameter
) {
  return { name, age, hobbies };
}

const user = createUser("John", 30, "Reading", "Swimming");
console.log(user);
rust
// Function handling various parameter types in Rust
// ฟังก์ชันที่จัดการพารามิเตอร์หลายรูปแบบใน Rust
fn create_user(name: String, age: Option<u32>, hobbies: Vec<String>) -> (String, u32, Vec<String>) {
    let age = age.unwrap_or(18); // Set default value
    (name, age, hobbies)
}

fn main() {
    let (name, age, hobbies) = create_user(
        String::from("John"),
        Some(30),
        vec![String::from("Reading"), String::from("Swimming")]
    );
    println!("Name: {}, Age: {}, Hobbies: {:?}", name, age, hobbies);
}
python
# Function with various parameter types in Python
# ฟังก์ชันที่รับพารามิเตอร์หลายรูปแบบใน Python
def create_user(name, age=18, *hobbies):
    return {
        'name': name,
        'age': age,
        'hobbies': hobbies
    }

user = create_user('John', 30, 'Reading', 'Swimming')
print(user)
go
// Function with various parameter types in Go
// ฟังก์ชันที่รับพารามิเตอร์หลายรูปแบบใน Go
package main

import "fmt"

func createUser(name string, age int, hobbies []string) map[string]interface{} {
    if age == 0 {
        age = 18 // Default value
    }
    return map[string]interface{}{
        "name":    name,
        "age":     age,
        "hobbies": hobbies,
    }
}

func main() {
    user := createUser("John", 30, []string{"Reading", "Swimming"})
    fmt.Println(user)
}

Higher-order Functions (ฟังก์ชันขั้นสูง)

js
// Higher-order functions in JavaScript
// Higher-order functions ใน JavaScript
const numbers = [1, 2, 3, 4, 5];

// Function that takes a function as parameter
// ฟังก์ชันที่รับฟังก์ชันเป็นพารามิเตอร์
const double = nums => nums.map(n => n * 2);
console.log(double(numbers)); // [2, 4, 6, 8, 10]

// Function that returns a function
// ฟังก์ชันที่ส่งคืนฟังก์ชัน
const multiplier = factor => n => n * factor;
const triple = multiplier(3);
console.log(triple(5)); // 15
rust
// Higher-order functions in Rust
// Higher-order functions ใน Rust
fn main() {
    let numbers = vec![1, 2, 3, 4, 5];
    
    // Function that takes a function as parameter
    // ฟังก์ชันที่รับฟังก์ชันเป็นพารามิเตอร์
    let doubled: Vec<i32> = numbers.iter().map(|n| n * 2).collect();
    println!("{:?}", doubled); // [2, 4, 6, 8, 10]
    
    // Function that returns a function
    // ฟังก์ชันที่ส่งคืนฟังก์ชัน
    fn multiplier(factor: i32) -> Box<dyn Fn(i32) -> i32> {
        Box::new(move |n| n * factor)
    }
    let triple = multiplier(3);
    println!("{}", triple(5)); // 15
}
python
# Higher-order functions in Python
# Higher-order functions ใน Python
numbers = [1, 2, 3, 4, 5]

# Function that takes a function as parameter
# ฟังก์ชันที่รับฟังก์ชันเป็นพารามิเตอร์
def double(nums):
    return list(map(lambda n: n * 2, nums))
print(double(numbers))  # [2, 4, 6, 8, 10]

# Function that returns a function
# ฟังก์ชันที่ส่งคืนฟังก์ชัน
def multiplier(factor):
    def multiply(n):
        return n * factor
    return multiply
triple = multiplier(3)
print(triple(5))  # 15
go
// Higher-order functions in Go
// Higher-order functions ใน Go
package main

import "fmt"

func main() {
    numbers := []int{1, 2, 3, 4, 5}
    
    // Function that takes a function as parameter
    // ฟังก์ชันที่รับฟังก์ชันเป็นพารามิเตอร์
    double := func(nums []int, fn func(int) int) []int {
        result := make([]int, len(nums))
        for i, n := range nums {
            result[i] = fn(n)
        }
        return result
    }
    
    doubled := double(numbers, func(n int) int {
        return n * 2
    })
    fmt.Println(doubled) // [2 4 6 8 10]
    
    // Function that returns a function
    // ฟังก์ชันที่ส่งคืนฟังก์ชัน
    multiplier := func(factor int) func(int) int {
        return func(n int) int {
            return n * factor
        }
    }
    
    triple := multiplier(3)
    fmt.Println(triple(5)) // 15
}