string - 为什么我不能像在 trim_right_matches() 中那样在 trim_matches() 中使用 &str?

标签 string rust pattern-matching

trim_right_matches 中,我可以传递一个字符串值:

println!("{}", "[(foo)]".trim_right_matches(")]"));
// [(foo

但是,我不能在 trim_matches 中使用字符串值:

println!("{}", "[(foo)]".trim_matches("[()]"));

因为我收到以下错误:

error[E0277]: the trait bound `std::str::pattern::StrSearcher<'_, '_>: std::str::pattern::DoubleEndedSearcher<'_>` is not satisfied
 --> test.rs:2:27
  |
2 |     println!("{}", "[(foo)]".trim_matches("[()]"));
  |                              ^^^^^^^^^^^^ the trait `std::str::pattern::DoubleEndedSearcher<'_>` is not implemented for `std::str::pattern::StrSearcher<'_, '_>`
error: aborting due to previous error

以下代码有效:

println!("{}", "[(foo)]".trim_matches(&['(', '[', ']', ')'] as &[_]));
// foo

但是,它很长,不像单个字符串值那样容易阅读;我希望能够像 trim_right_matches 一样使用字符串值。

最佳答案

这两个函数具有相似的签名,但如果仔细观察,您会发现它们的搜索模式实际上不同:

trim_right_matches:

pub fn trim_right_matches<'a, P>(&'a self, pat: P) -> &'a str
where
    P: Pattern<'a>,
    <P as Pattern<'a>>::Searcher: ReverseSearcher<'a> // ReverseSearcher

trim_matches:

pub fn trim_matches<'a, P>(&'a self, pat: P) -> &'a str
where
    P: Pattern<'a>,
    <P as Pattern<'a>>::Searcher: DoubleEndedSearcher<'a> // DoubleEndedSearcher

the docs for DoubleEndedSearcher您可以找到为什么 &str 不能是 DoubleEndedSearcher 的解释:

(&str)::Searcher is not a DoubleEndedSearcher because the pattern "aa" in the haystack "aaa" matches as either "[aa]a" or "a[aa]", depending from which side it is searched.

至于为什么您的解决方法有效:

"[(foo)]".trim_matches(&['(', '[', ']', ')'] as &[_]));

因为它实际上不是在&str上匹配,而是在&[char]上匹配,它不是字符串切片而是字符数组的切片,这是一个有效的 DoubleEndedSearcher

关于string - 为什么我不能像在 trim_right_matches() 中那样在 trim_matches() 中使用 &str?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49856439/

相关文章:

scala - Scala中通用类型的模式匹配

c++ - 匹配小的灰度图像

c# - 如何删除文本框上的小写字母?

c# - 在字符串数组中找到最短的字符串

swift - 我应该使用哪个 Swift 字符数来删除(第一个 :)?

sql - Postgres和Rust R2D2 : How to get array_to_json as text/string without the escaped double quotes?

assembly - 如何读取这段Rust代码的汇编代码?

c - 如何使用 C 中的 stdio.h 逐字读取文件?

debugging - 在 Rust 中调试时执行语句

haskell - 为什么不是 (20 >) 。长度 。取 10 === const True