rust - 这个 for 循环模式有没有名字,如果有,有没有更好的写法?

标签 rust semantics idioms

这是我所指模式的示例函数:

fn check_sub_listiness<T: PartialEq>(big_list: &[T], small_list: &[T]) -> bool {
    for poss_sublist in big_list.windows(small_list.len()) {
        if poss_sublist == small_list {
            return true;
        }
    }
    false
}
此代码接受一个大列表和一个小列表,并返回小列表是否是大列表的子列表。我把它写成我正在做的锻炼练习的一部分。
我发现自己经常使用这种模式,在那里我遍历一些选项,检查条件,如果找到则返回 true,如果我在循环结束时没有找到我要找的内容,则返回 false。有这个名字吗?更重要的是,是否有更好的语义方式来编写它(用 Rust 或任何其他语言)。

最佳答案

迭代直到成功就像 .find() 但如果您只对 true 感兴趣/false结果你可以使用 .any() ,这正是您所要求的。

Tests if any element of the iterator matches a predicate.

any() takes a closure that returns true or false. It applies this closure to each element of the iterator, and if any of them return true, then so does any(). If they all return false, it returns false.

any() is short-circuiting; in other words, it will stop processing as soon as it finds a true, given that no matter what else happens, the result will also be true.

An empty iterator returns false.


所以你的循环可以这样写:
fn check_sub_listiness<T: PartialEq>(big_list: &[T], small_list: &[T]) -> bool {
    big_list.windows(small_list.len()).any(|poss_sublist| {
        poss_sublist == small_list
    })
}

关于rust - 这个 for 循环模式有没有名字,如果有,有没有更好的写法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65246679/

相关文章:

rust - 无法通过 arm-none-eabi-gdb 命令连接到 GDB 服务器

rust - 为什么 Rust 的 ChunksExact<T> 没有在编译时已知的大小

指向非静态方法的指针的 C++ 有用性

ruby - 为什么 ruby​​ 中的变量前缀允许在方法调用中省略括号?

python - 从嵌套字典中获取值

enums - 从没有模式匹配的枚举中读取

serialization - 使用#[serde(untagged)] 和#[serde(with)] 的组合反序列化枚举

rust - 在不复制操作数的情况下重载 Add-operator

java - 根据调查构建人类可读的句子

oop - 对象集合、对象聚合、对象关联和对象组合之间有什么区别?