gpt4 book ai didi

module - 使用与结构同名的子模块的特征

转载 作者:行者123 更新时间:2023-11-29 07:46:10 25 4
gpt4 key购买 nike

尝试编译以下 Rust 代码

mod traits {
pub trait Dog {
fn bark(&self) {
println!("Bow");
}
}
}

struct Dog;

impl traits::Dog for Dog {}

fn main() {
let dog = Dog;
dog.bark();
}

给出错误信息

error[E0599]: no method named `bark` found for type `Dog` in the current scope
--> src/main.rs:15:9
|
9 | struct Dog;
| ----------- method `bark` not found for this
...
15 | dog.bark();
| ^^^^
|
= 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 crate::traits::Dog;
|

如果我添加 use crate::traits::Dog;,错误变为:

error[E0255]: the name `Dog` is defined multiple times
--> src/main.rs:11:1
|
1 | use crate::traits::Dog;
| ------------------ previous import of the trait `Dog` here
...
11 | struct Dog;
| ^^^^^^^^^^^ `Dog` redefined here
|
= note: `Dog` must be defined only once in the type namespace of this module

如果我将 trait Dog 重命名为 trait DogTrait,一切正常。如何使用与主模块中的结构同名的子模块中的特征?

最佳答案

您可以在导入特征时重命名特征以获得相同的结果,而无需全局重命名特征:

use traits::Dog as DogTrait;

编译器现在甚至建议:

help: you can use `as` to change the binding name of the import
|
1 | use crate::traits::Dog as OtherDog;
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

documentation

关于module - 使用与结构同名的子模块的特征,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30685529/

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