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

Iter Functions

Iterator creation และ utility functions ใน std::iter module สำหรับสร้างและ manipulate iterators

Functions สำหรับสร้าง iterators จาก scratch

use std::iter;
fn main() {
// repeat - infinite iterator of same value
let fives: Vec<_> = iter::repeat(5).take(5).collect();
println!("repeat: {:?}", fives);
// repeat_with - infinite from closure (lazy)
let mut counter = 0;
let nums: Vec<_> = iter::repeat_with(|| {
counter += 1;
counter
}).take(5).collect();
println!("repeat_with: {:?}", nums);
// once - single element
let single: Vec<_> = iter::once(42).collect();
println!("once: {:?}", single);
// once_with - single from closure (lazy)
let computed: Vec<_> = iter::once_with(|| {
println!("Computing...");
42
}).collect();
println!("once_with: {:?}", computed);
// empty - no elements
let empty: Vec<i32> = iter::empty().collect();
println!("empty: {:?}", empty);
// from_fn - from closure that returns Option
let mut count = 0;
let limited: Vec<_> = iter::from_fn(|| {
if count < 5 {
count += 1;
Some(count)
} else {
None
}
}).collect();
println!("from_fn: {:?}", limited);
}

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

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