[英]Why does the Split type only return &str even though Pattern has implementations for both &str and char?
I'm having a hard time understanding how the Split
type works in Rust. 我很难理解
Split
类型在Rust中的工作方式。
Split<'a, P> where P: Pattern<'a>
is the type returned by the std::string::String::split
method. Split<'a, P> where P: Pattern<'a>
是std::string::String::split
方法返回的类型。 The type has an implementation for Iterator<'a, P>
, where P
is still the Pattern
type, but in reality (and as I would expect) the Iterator
only returns &str
slices. 该类型具有
Iterator<'a, P>
,其中P
仍然是Pattern
类型,但实际上(并且正如我所期望的那样), Iterator
仅返回&str
切片。
Eg, split(p).collect::<Vec<&str>>()
works but split(p).collect::<Vec<char>>()
results a compiler error. 例如,
split(p).collect::<Vec<&str>>()
可以工作,但是split(p).collect::<Vec<char>>()
导致编译器错误。 This is what I would expect to happen, but I don't understand how it happens since Pattern
has implementations for both &str
and char
. 这是我希望发生的事情,但是由于
Pattern
同时为&str
和char
实现,所以我不知道它是如何发生的。
Why isn't the Split
type simply defined as Split<'a, &'a str>
, since it is effectively an Iterator
over &str
s? 为什么不将
Split
类型简单定义为Split<'a, &'a str>
,因为它实际上是对&str
的Iterator
? Why does it behave as if it is effectively defined as that? 为什么它的行为好像被有效地定义为那样?
The type has an implementation for
Iterator<'a, P>
该类型具有
Iterator<'a, P>
It doesn't. 没有。 It's just
Iterator
, which has no type parameters. 只是
Iterator
,没有类型参数。 Every implementation of Iterator
must declare the type of the item that it iterates over using an associated type. Iterator
每个实现都必须使用关联的类型声明要Iterator
的项的类型。 For example, Split
's implementation [1] is something like this: 例如,
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 asSplit<'a, &'a str>
, since it is effectively anIterator
over&str
s?为什么不将
Split
类型简单定义为Split<'a, &'a str>
,因为它实际上是对&str
的Iterator
?
Because iterators are lazy. 因为迭代器是惰性的。 The
Split
struct still needs to know about the pattern in order to match the next item. Split
结构仍需要了解模式才能匹配下一项。 Its iterator instance has Item = &str
, because that is what it iterates over. 它的迭代器实例具有
Item = &str
,因为这是对其进行迭代的内容。
[1] The actual implementation is generated by a macro . [1]实际的实现是由宏生成的 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.