【问题标题】:Why does the Split type only return &str even though Pattern has implementations for both &str and char?为什么即使 Pattern 具有 &str 和 char 的实现,Split 类型只返回 &str?
【发布时间】:2018-10-24 07:16:30
【问题描述】:

我很难理解 Split 类型在 Rust 中是如何工作的。

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

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

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

【问题讨论】:

  • Iterator 的输出类型不是它的类型参数,而是它的Item 关联类型。
  • 您将Iterator (P) 的泛型参数与其Item 关联类型混淆了。

标签: generics rust iterator traits associated-types


【解决方案1】:

该类型具有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> { ... }
}

为什么Split 类型不简单地定义为Split&lt;'a, &amp;'a str&gt;,因为它实际上是Iterator 而不是&amp;strs?

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


[1]实际实现是generated by a macro

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-21
    • 2023-03-16
    • 1970-01-01
    • 2022-06-15
    • 2018-11-13
    • 2018-06-27
    • 2020-08-25
    • 2021-11-07
    相关资源
    最近更新 更多