Skip to content
เข้าสู่ระบบ

Fn and Never Primitives

Function types และ never type

fn main() {
// Function pointer type
fn add(a: i32, b: i32) -> i32 { a + b }
fn multiply(a: i32, b: i32) -> i32 { a * b }
// fn is a type
let op: fn(i32, i32) -> i32 = add;
println!("add(2, 3) = {}", op(2, 3));
let op: fn(i32, i32) -> i32 = multiply;
println!("multiply(2, 3) = {}", op(2, 3));
// Array of function pointers
let operations: [fn(i32, i32) -> i32; 2] = [add, multiply];
for (i, op) in operations.iter().enumerate() {
println!("operations[{}](4, 5) = {}", i, op(4, 5));
}
// Function as parameter
fn apply(f: fn(i32) -> i32, x: i32) -> i32 {
f(x)
}
fn double(x: i32) -> i32 { x * 2 }
println!("apply(double, 10) = {}", apply(double, 10));
// Size of function pointer
println!("Size of fn pointer: {} bytes", std::mem::size_of::<fn()>());
}

เข้าสู่ระบบเพื่อดูเนื้อหาเต็ม

ยืนยันตัวตนด้วยบัญชี Google เพื่อปลดล็อกบทความทั้งหมด