【Rust】迭代器-any

环境

  • Rust 1.56.1
  • VSCode 1.61.2

概念

参考:https://doc.rust-lang.org/stable/rust-by-example/fn/closures/closure_examples/iter_any.html

示例

前面学习了闭包,现在看看标准库中的例子:Iterator::any。

Iterator

pub trait Iterator {
    // The type being iterated over.
    type Item;

    // `any` takes `&mut self` meaning the caller may be borrowed
    // and modified, but not consumed.
    fn any<F>(&mut self, f: F) -> bool where
        // `FnMut` meaning any captured variable may at most be
        // modified, not consumed. `Self::Item` states it takes
        // arguments to the closure by value.
        F: FnMut(Self::Item) -> bool {}
}

Vector

fn main() {
    let vec1 = vec![1, 2, 3];
    let vec2 = vec![4, 5, 6];

    // 迭代为 i32 的引用,使用了解构。
    println!("2 in vec1: {}", vec1.iter().any(|&x| x == 2));
    // 直接捕获值
    println!("2 in vec2: {}", vec2.into_iter().any(|x| x == 2));
}

Array

fn main() {
    let array1 = [1, 2, 3];
    let array2 = [4, 5, 6];

    // 解构
    println!("2 in array1: {}", array1.iter().any(|&x| x == 2));
    // 移动
    println!("2 in array2: {}", array2.into_iter().any(|x| x == 2));
}

总结

了解了 Rust 中迭代器的 any 方法使用闭包的方式。

附录

posted @   jiangbo4444  阅读(170)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
点击右上角即可分享
微信分享提示