Rust के महत्वपूर्ण विषय
Rust Iterators: map, filter, collect
Process a collection as a pipeline: keep some items, change them and gather the result.
आप क्या सीखेंगे
- iter, filter and map
- collect and sum
- enumerate and take
Even squares of 1 to 6
- 1
iter()1 2 3 4 5 6 - 2
filter2 4 6 - 3
map4 16 36 - 4
collect[4, 16, 36]
A lazy pipeline
An iterator produces the items of a collection one at a time. Methods such as filter and map build a new iterator, and methods such as collect and sum run it and produce a result.
Iterators are lazy: filter and map do nothing until collect asks for the items. sum needs the result type, here i32. max returns an Option because the list could be empty. enumerate adds the index and take(2) stops after two items.
मुख्य बातें
- filter and map do nothing until a result is asked for.
- collect gathers the items into a Vec.
- max returns an Option.
चलने योग्य Rust उदाहरण
Rust
main.rs
fn main() {
let numbers = vec![1, 2, 3, 4, 5, 6];
let even_squares: Vec<i32> = numbers
.iter()
.filter(|n| *n % 2 == 0)
.map(|n| n * n)
.collect();
println!("{:?}", even_squares);
let total: i32 = numbers.iter().sum();
let max = numbers.iter().max();
println!("total = {total}, max = {:?}", max);
for (index, value) in numbers.iter().enumerate().take(2) {
println!("{index}: {value}");
}
let any_big = numbers.iter().any(|&n| n > 5);
println!("any above 5: {any_big}");
}
[4, 16, 36]
total = 21, max = Some(6)
0: 1
1: 2
any above 5: trueअभ्यास
उदाहरण को ऑनलाइन कंपाइलर में खोलें, कोई मान बदलें या एक पंक्ति जोड़ें, और चलाने से पहले आउटपुट का अनुमान लगाएँ। फिर कोड में जान-बूझकर गलती करें और कंपाइलर का संदेश पढ़ें।
यह पाठ पूरा कर लिया?
अपनी प्रगति ट्रैक करने के लिए इसे सीखा हुआ मार्क करें।
आपकी प्रगति इस ब्राउज़र में सेव है इसे हर डिवाइस पर रखने के लिए साइन इन करें।
चैलेंज से अभ्यास करें
इस पाठ में सीखी बात से एक असली समस्या हल करें। हर चैलेंज ब्राउज़र में चलता है, तुरंत टेस्ट और AI रिव्यू के साथ।
- Above-Average Values Keep the values that are greater than the average. आसान
- डुप्लिकेट हटाएँ प्रत्येक मान की केवल पहली उपस्थिति रखें। आसान