2015-06-06 11 views
5

Cercando di compilare il codice Rust follwingUsa tratto dal modulo con lo stesso nome struct

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

struct Dog; 

impl traits::Dog for Dog {} 

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

dà il messaggio di errore

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

Se aggiungo use traits::Dog;, l'errore diventa:

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

Se si rinomina trait Dog in trait DogTrait, tutto funziona. Ma come posso usare un tratto da un sottomodulo che ha lo stesso nome di una struct nel mio modulo principale?

risposta

4

Non so che sia possibile importarli entrambi, poiché i nomi sono in conflitto. Vedere llogiq's answer per come importare entrambi.

Se non si desidera importare sia (o non può per qualsiasi ragione), è possibile utilizzare Universale Function Call Sintassi (UFCS) per utilizzare il metodo del tratto direttamente:

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

Si potrebbe fare quanto segue per ottenere lo stesso risultato senza rinominare il tratto globalmente:

use traits::Dog as DogTrait; 

(some documentation)

Problemi correlati