gpt4 book ai didi

rust - 添加和+之间的区别?

转载 作者:行者123 更新时间:2023-11-29 08:34:27 25 4
gpt4 key购买 nike

<分区>

我正在阅读 Rust by Examples .

下面的代码有效。

println!("Bar + Foo = {:?}", Bar + Foo);

但是,尽管 struct 和 trait 实现都在范围内,但以下内容不起作用。

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;
|

为什么不呢?

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com