rust - 添加和+之间的区别?
问题描述
我正在阅读Rust by Examples。
下面的代码有效。
println!("Bar + Foo = {:?}", Bar + Foo);
但是,尽管结构和特征实现都在范围内,但下面不起作用。
println!("Bar + Foo = {:?}", Bar.add(Foo));
完整代码:
use std::ops;
struct Foo;
struct Bar;
#[derive(Debug)]
struct FooBar;
impl ops::Add<Bar> for Foo {
type Output = FooBar;
fn add(self, _rhs: Bar) -> FooBar {
println!("> Foo.add(Bar) was called");
FooBar
}
}
fn main() {
println!("Foo + Bar = {:?}", Foo + Bar);
println!("Foo + Bar = {:?}", Foo.add(Bar));
}
错误:
error[E0599]: no method named `add` found for type `Foo` in the current scope
--> src/main.rs:21:38
|
3 | struct Foo;
| ----------- method `add` not found for this
...
21 | println!("Foo + Bar = {:?}", Foo.add(Bar));
| ^^^
|
= help: items from traits can only be used if the trait is in scope
help: the following trait is implemented but not in scope, perhaps add a `use` for it:
|
1 | use std::ops::Add;
|
为什么不?
解决方案
正如编译器所说:
仅当特征在范围内时,才能使用特征中的项目
只需按照编译器的建议执行即可:
use std::ops::Add;
fn main() {
println!("Foo + Bar = {:?}", Foo + Bar);
println!("Foo + Bar = {:?}", Foo.add(Bar));
}
要清楚:
“尽管结构和特征实现都在范围内,但下面不起作用”
这是不正确的,特征Add
不在范围内,您只有ops
模块,这与use std::ops::Add;
. 您还可以看到,在您的实现中,您编写ops::Add<Bar>
not Add<Bar>
so Add
is not in your code just 的范围ops
。
如果特征中的项目只能在特征在范围内时使用,那么“Foo + Bar”如何工作?“+”和“加”有什么区别?
+
只是一个语法糖,编译器为你做的一件神奇的事情。它是如何工作的并不重要,+
不需要调用任何东西add()
(因为它是内置的,编译器“知道”要做什么)但是如果你自己调用它,编译器没有理由不应用关于 trait 和还有关于在范围内导入此特征的规则(默认情况下某些特征是导入但不是Add
)。+
是特殊的,但不是Add
特质。这同样适用于?
操作员和更多的生锈。我们使用 trait 来实现一些基本的操作符,这真的很干净而且非常灵活。
推荐阅读
- excel - Excel VBA代码将多个范围复制到另一个工作簿中的特定工作表
- javascript - 添加本地 json 文件以在 React 中获取对象
- python - Python:执行python代码时没有任何反应(P2P实现)
- java - 是否有任何解决方案可以在不同的方法中仅使用 1 个 findViewById
- javascript - 如何使用 JavaScript 在 div 中插入多个元素?
- javascript - react js中的“Readonly<{}>”类型不存在属性“currentTime”
- php - 尝试使用 swift mailer 从节点访问值以在电子邮件模板中呈现
- python - 如果在 lambda 中使用 python 关闭,如何 ping 和启动 EC2 实例
- r - 保持绘图的分辨率但在 R 中压缩大小
- apache-flink - 在 flink 中进行连接操作时出现 OutOfMemoryError