You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为Rust的ends_with函数传递多个后缀且无需for循环?

多后缀匹配的无手动循环实现方案

你可以利用Rust标准库中的迭代器方法any来实现,无需手动编写for循环:

首先修正你的代码问题:原代码中s.ends_with(e)无法编译,因为Vec<&str>没有实现Pattern trait(ends_with要求的参数类型)。改用迭代器的any方法可以简洁解决这个问题:

fn check_str(s: &str, endings: &[&str]) -> bool {
    // any会遍历后缀列表,只要有一个后缀匹配就返回true
    endings.iter().any(|&ending| s.ends_with(ending))
}

fn main() {
    let endings = vec!["o", "a"];
    println!("{}", check_str("hello", &endings)); // 输出true
    println!("{}", check_str("world", &endings)); // 输出false
}

说明

  • any是迭代器的内置方法,它会遍历迭代器中的每个元素,只要有一个元素满足闭包中的条件(这里是s.ends_with(ending)),就立即返回true,否则遍历完所有元素后返回false。
  • 把参数e: Vec<&str>改成e: &[&str]是为了避免不必要的所有权转移,让函数更灵活(可以接收切片、Vec的引用等)。

这种写法没有手动编写for循环的冗余代码,同时保持了代码的可读性和效率。

内容的提问来源于stack exchange,提问作者Alexey Mirano

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 08:01:43