这是我所指模式的示例函数:
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 returnstrue
orfalse
. It applies this closure to each element of the iterator, and if any of them returntrue
, then so doesany()
. If they all returnfalse
, it returnsfalse
.
any()
is short-circuiting; in other words, it will stop processing as soon as it finds atrue
, given that no matter what else happens, the result will also betrue
.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/