为什么我不能在拆分时调用 next_back()?



Split的文档说它实现了DoubleEndedIterator,它应该有一个获取最后一个元素的next_back()方法。

但是当我这样做时:

fn get_file_ext(file_name: &str) -> Option<String> {
if let Some(ext) = file_name.split(".").next_back() {
return Some(ext.to_owned());
}
None
}

我收到此错误:

error[E0599]: no method named `next_back` found for struct `std::str::Split<'_, &str>` in the current scope
--> src/lib.rs:2:45
|
2   |       if let Some(ext) = file_name.split(".").next_back() {
|                                               ^^^^^^^^^ method not found in `std::str::Split<'_, &str>`
|
= note: the method `next_back` exists but the following trait bounds were not satisfied:
`std::str::pattern::StrSearcher<'_, '_>: std::str::pattern::DoubleEndedSearcher<'_>`
which is required by `std::str::Split<'_, &str>: std::iter::DoubleEndedIterator`

"the following trait bounds were not satisfied"是什么意思?

解决方案

取代

file_name.split(".")

file_name.split('.')

解释

下面是特征实现声明:

impl<'a, P> DoubleEndedIterator for Split<'a, P>
where
P: Pattern<'a>,
<P as Pattern<'a>>::Searcher: DoubleEndedSearcher<'a>, 

这里绑定的缺失特征是

<P as Pattern<'a>>::Searcher: DoubleEndedSearcher<'a>,

此特征绑定是为char的搜索者实现的,而不是为&str实现的。

请参阅DoubleEndedSearcher

char::Searcher是一个DoubleEndedSearcher,因为搜索char只需要一次查看一个,其行为与 两端。

(&str)::Searcher不是DoubleEndedSearcher,因为模式"aa"在干草堆中,"aaa"匹配为"[aa]a""a[aa]",具体取决于 从哪一侧搜索。

否则:并非所有模式都允许双端搜索。char允许它,但不允许字符串。

最新更新