Use a dash from a submodule with the same name as the structure

Trying to compile the following Rust code

mod traits { pub trait Dog { fn bark(&self) { println!("Bow"); } } } struct Dog; impl traits::Dog for Dog {} fn main() { let dog = Dog; dog.bark(); } 

gives an error message

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

If I add use crate::traits::Dog; , an error will appear:

 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 

If I rename trait Dog to trait DogTrait , everything will work. How can I use a dash from a submodule with the same name as the structure in my main module?

+6
source share
2 answers

You can rename a characteristic during import to get the same result without renaming the attribute globally:

 use traits::Dog as DogTrait; 

The compiler now even offers this:

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

documentation

+6
source

If you do not want to import both (or cannot for any reason), you can use fully qualified syntax (FQS) to directly use the trait method:

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

All Articles