在 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 aDoubleEndedSearcher
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/