rust - "method exists but trait bounds not satisfied"是什么意思?

标签 rust

我是 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);
}

它编译。<​​/p>

这里发生了什么?当 Rust 说方法 ... 存在但不满足以下特征边界 时,Rust 是什么意思?

最佳答案

方法all()Iterator 的一种方法trait,因此您只能在实现该 trait 的类型上调用它。类型Range<char>没有实现 Iterator trait,因为在一般情况下,Unicode 字符的范围没有明确定义。有效的 Unicode 代码点集有间隙,构建代码点范围通常被认为没有用。类型Range<u8>另一方面确实实现了Iterator ,因为迭代一系列字节具有明确定义的含义。

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

关于rust - "method exists but trait bounds not satisfied"是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56296864/

相关文章:

closures - 我的代码中的非法移动在哪里?

visual-studio-code - 如何在 VSCode 中使用 rust-analyzer 打字时启用实时 linting?

generics - 使用泛型函数制作盒装特征会返回错误

rust - 在 S<T> 上使用通用特征强制我让 T 比 S 长寿

for-loop - Rust 中 for 循环的命名中断

rust - 如何在 Rust 中从另一个字符中减去一个字符?

string - 如何在 Rust 中更改字符串中特定索引处的字符?

rust - 为什么通过 `for` 循环迭代集合在 Rust 中被认为是 "move"?

closures - 为闭包类型别名实现特征

rust - 如何实现通用函数的专用版本?