使用与struct相同名称的子模块中的trait

nwe*_*hof 7 module traits rust

试图编译下面的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();
}
Run Code Online (Sandbox Code Playgroud)

给出错误消息

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;
   |
Run Code Online (Sandbox Code Playgroud)

如果我添加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
Run Code Online (Sandbox Code Playgroud)

如果我重新命名trait Dogtrait DogTrait,一切正常.但是,如何使用与主模块中的结构名称相同的子模块中的特征?

llo*_*giq 7

您可以执行以下操作以获得相同的结果,而无需全局重命名特征:

use traits::Dog as DogTrait;
Run Code Online (Sandbox Code Playgroud)

(一些文件)


She*_*ter 5

如果您不想同时导入两者(或由于某种原因而不能导入),则可以使用完全限定语法(FQS)直接使用特征的方法:

fn main() {
    let dog = Dog;
    traits::Dog::bark(&dog);
}
Run Code Online (Sandbox Code Playgroud)