为什么 Split 类型只有 return &str,即使 Pattern 有 &str 和 char 的实现?

Why does the Split type only return &str even though Pattern has implementations for both &str and char?

我很难理解 Split 类型在 Rust 中的工作方式。

Split<'a, P> where P: Pattern<'a>std::string::String::split方法返回的类型。该类型有一个 Iterator<'a, P> 的实现,其中 P 仍然是 Pattern 类型,但实际上(正如我所期望的) Iterator 只有 returns &str 片。

例如,split(p).collect::<Vec<&str>>() 有效,但 split(p).collect::<Vec<char>>() 导致编译器错误。这是我希望发生的事情,但我不明白它是如何发生的,因为 Pattern&strchar.

都有实现

为什么 Split 类型不简单定义为 Split<'a, &'a str>,因为它实际上是 &str 之上的 Iterator?为什么它的行为就像它被有效定义一样?

The type has an implementation for Iterator<'a, P>

没有。它只是 Iterator,没有类型参数。 Iterator 的每个实现都必须声明它使用关联类型迭代的项目的类型。例如,Split的实现[1]是这样的:

impl <'a, P> Iterator for Split<'a, P> {
    type Item = &'a str;
    fn next(&mut self) -> Option<&'a str> { ... }
}

Why isn't the Split type simply defined as Split<'a, &'a str>, since it is effectively an Iterator over &strs?

因为迭代器是惰性的。 Split 结构仍然需要了解模式才能匹配下一项。它的迭代器实例有 Item = &str,因为这是它迭代的对象。


[1]实际执行是generated by a macro.