“方法存在但特征边界不满足"是什么意思? [英] What does it mean when "method exists but trait bounds not satisfied"?
问题描述
我是 Rust 的新手,观察到一些我无法反驳的东西.
当我写
fn main() {('a'..'z').all(|_| true);}
编译器报错:
error[E0599]: 在当前范围内没有找到类型为 `std::ops::Range<char>` 的名为 `all` 的方法-->src/main.rs:2:16|2 |('a'..'z').all(|_| 真)|^^^|= 注意:方法 `all` 存在,但不满足以下特征边界:`std::ops::Range: std::iter::Iterator`
当我把它改成
fn main() {(b'a'..b'z').all(|_| 真);}
它编译.</p>
这里发生了什么?Rust 说方法......存在但不满足以下特征边界
是什么意思?
all()
方法是 Iterator
trait 的一个方法,所以你只能调用它在实现该特征的类型上.类型 Range
没有实现 Iterator
特性,因为在一般情况下,Unicode 字符的范围没有明确定义.一组有效的 Unicode 代码点存在差距,构建一系列代码点通常不被认为是有用的.另一个类型 Range
确实实现了 Iterator
,因为在一个字节范围内迭代具有明确定义的含义.
更一般地,错误消息告诉您 Rust 找到了一个具有正确名称的方法,但该方法不适用于您调用它的类型.
I'm new to Rust and observed something that I couldn't reason against.
When I write
fn main() {
('a'..'z').all(|_| true);
}
The compiler reports an error:
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`
When I change it to
fn main() {
(b'a'..b'z').all(|_| true);
}
it compiles.
What's happening here? What does Rust mean when it says the method ... exists but the following trait bounds were not satisfied
?
The method all()
is a method of the Iterator
trait, so you can only call it on types that implement that trait. The type Range<char>
does not implement the Iterator
trait, since a range of Unicode characters is not well-defined in the general case. The set of valid Unicode code points has gaps, and building a range of code points is not in general considered useful. The type Range<u8>
on the other does implement Iterator
, since iterating over a range of bytes has a well-defined meaning.
More generally, the error message tells you that Rust has found a method with the correct name, but that method does not apply to the type you call it for.
这篇关于“方法存在但特征边界不满足"是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!