首页 > 解决方案 > 添加和+之间的区别?

问题描述

我正在阅读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;
   |

为什么不?

标签: rustaddtraits

解决方案


正如编译器所说:

仅当特征在范围内时,才能使用特征中的项目

只需按照编译器的建议执行即可:

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 Addis not in your code just 的范围ops

如果特征中的项目只能在特征在范围内时使用,那么“Foo + Bar”如何工作?“+”和“加”有什么区别?

+只是一个语法糖,编译器为你做的一件神奇的事情。它是如何工作的并不重要,+不需要调用任何东西add()(因为它是内置的,编译器“知道”要做什么)但是如果你自己调用它,编译器没有理由不应用关于 trait 和还有关于在范围内导入此特征的规则(默认情况下某些特征是导入但不是Add)。+是特殊的,但不是Add特质。这同样适用于?操作员和更多的生锈。我们使用 trait 来实现一些基本的操作符,这真的很干净而且非常灵活。


推荐阅读