【问题标题】:What does it mean when "method exists but trait bounds not satisfied"?“方法存在但不满足特征界限”是什么意思?
【发布时间】:2019-10-11 07:20:14
【问题描述】:

我是 Rust 新手,发现了一些我无法反驳的东西。

当我写作时

fn main() {
    ('a'..'z').all(|_| true);
}

编译器报错:

error[E0599]: no method named `all` found for type `std::ops::Range<char>` in the current scope
 --> src/main.rs:2:16
  |
2 |     ('a'..'z').all(|_| true)
  |                ^^^
  |
  = note: the method `all` exists but the following trait bounds were not satisfied:
          `std::ops::Range<char> : std::iter::Iterator`

当我把它改成

fn main() {
    (b'a'..b'z').all(|_| true);
}

它编译。

这里发生了什么? Rust 说 the method ... exists but the following trait bounds were not satisfied 是什么意思?

【问题讨论】:

标签: rust


【解决方案1】:

all() 方法是 Iterator 特征的方法,因此您只能在实现该特征的类型上调用它。 Range&lt;char&gt; 类型没有实现 Iterator 特征,因为在一般情况下,Unicode 字符的范围没有明确定义。有效的 Unicode 代码点集存在差距,构建一系列代码点通常被认为没有用处。另一个类型 Range&lt;u8&gt; 确实实现了 Iterator,因为迭代一系列字节具有明确定义的含义。

更一般地说,错误消息告诉你 Rust 找到了一个名称正确的方法,但该方法不适用于你调用它的类型。

【讨论】:

    【解决方案2】:

    这意味着作用域中有一个具有该名称的函数的特征,但您正在使用的对象没有实现这样的特征。

    在您的特定情况下,包含 all 方法的特征是 std::iter::Iterator,但您的对象 ('a'..'z') 如果类型为 Range&lt;char&gt; 则没有实现它。

    奇怪的是,您的第二个示例可以编译,因为 (b'a'..b'z') 的类型为 Range&lt;u8&gt;,它确实实现了 Iterator

    您可能想知道为什么Range&lt;char&gt; 没有实现迭代器。那是因为在有效值之间存在无效的char 值,所以这些范围不能被迭代。特别是,唯一有效的字符是 [0x0, 0xD7FF][0xE000, 0x10FFFF],IIRC 范围内的字符。

    【讨论】:

      猜你喜欢
      • 2021-01-17
      • 1970-01-01
      • 2022-11-27
      • 2022-01-20
      • 2019-10-28
      • 1970-01-01
      • 2021-08-23
      • 2021-07-13
      • 2019-05-11
      相关资源
      最近更新 更多