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

时间:2015-06-06 17:18:09

标签: module rust traits

尝试编译以下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();
}

给出错误消息

<anon>:13:9: 13:15 error: type `Dog` does not implement any method in scope named `bark`
<anon>:13     dog.bark();
                  ^~~~~~
<anon>:13:9: 13:15 help: methods from traits can only be called if the trait is in scope; the following trait is implemented but not in scope, perhaps add a `use` for it:
<anon>:13:9: 13:15 help: candidate #1: use `traits::Dog`

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

<anon>:1:5: 1:16 error: import `Dog` conflicts with type in this module [E0256]
<anon>:1 use traits::Dog;
             ^~~~~~~~~~~
<anon>:9:1: 9:12 note: note conflicting type here
<anon>:9 struct Dog;
         ^~~~~~~~~~~

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

2 个答案:

答案 0 :(得分:6)

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

use traits::Dog as DogTrait;

some documentation

答案 1 :(得分:4)

我不知道可以导入两者,因为名称冲突。有关如何导入两者的信息,请参阅llogiq's answer

如果您不想同时导入(或因任何原因不能导入),可以使用通用函数调用语法(UFCS)直接使用特征的方法:

fn main() {
    let dog = Dog;
    traits::Dog::bark(&dog);
}