Iterators & Closures
ใครชอบสไตล์ Functional Programming (เช่น .map().filter().reduce()) Rust จัดเต็มเรื่องนี้ครับ แถมประสิทธิภาพดีมากด้วย (Zero-Cost Abstractions) คือเขียนสวยแบบ High-level แต่ Compile ออกมาเร็วเท่า Loop ธรรมดา!
ลองนึกภาพว่า Iterator เป็นเหมือน “สายพานลำเลียง” ที่ส่งของมาทีละชิ้น แล้ว Closure เป็นเหมือน “พนักงานประจำจุด” ที่ทำงานกับของที่ผ่านมา!
1. Closures
Section titled “1. Closures”1.1 Basic Closure
Section titled “1.1 Basic Closure”fn main() { // ============================================ // Closure = anonymous function // |x| คือ parameter, ข้างหลังคือ body // ============================================ let add_one = |x| x + 1; let multiply = |x, y| x * y; let greet = || println!("Hello!");
println!("add_one(5) = {}", add_one(5)); // 6 println!("multiply(3, 4) = {}", multiply(3, 4)); // 12 greet(); // Hello!}เข้าสู่ระบบเพื่อดูเนื้อหาเต็ม
ยืนยันตัวตนด้วยบัญชี Google เพื่อปลดล็อกบทความทั้งหมด
Login with Google