Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use trait from submodule with same name as struct

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 the 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;, the error becomes:

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 works. How can I use a trait from a submodule that has the same name as a struct in my main module?

like image 828
nwellnhof Avatar asked Jun 06 '15 17:06

nwellnhof


Video Answer


2 Answers

You could rename the trait when importing it to get the same result without renaming the trait globally:

use traits::Dog as DogTrait;

The compiler now even suggests this:

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

documentation

like image 172
llogiq Avatar answered Oct 12 '22 02:10

llogiq


If you don't wish to import both (or can't for whatever reason), you can use Fully Qualified Syntax (FQS) to use the trait's method directly:

fn main() {
    let dog = Dog;
    traits::Dog::bark(&dog);
}
like image 32
Shepmaster Avatar answered Oct 12 '22 02:10

Shepmaster