2015-08-08 18 views
5

Sto cercando di trovare esempi per le funzioni di costruzione nei tratti, ma non ho avuto molta fortuna. È una cosa idiomatica da fare in Rust?È possibile avere una funzione di costruzione in un tratto?

trait A { 
    fn new() -> A; 
} 

struct B; 
impl A for B { 
    fn new() -> B { 
     B 
    } 
} 

fn main() { 
    println!("message") 
} 
<anon>:7:8: 9:9 error: method `new` has an incompatible type for trait: expected trait A, found struct `B` [E0053] 
<anon>:7  fn new() -> B { 
<anon>:8   B 
<anon>:9  } 
<anon>:7:8: 9:9 help: see the detailed explanation for E0053 
error: aborting due to previous error 
playpen: application terminated with error code 101 

Casting questo restituisce un nucleo :: :: marcatore errore relativo Sized.

trait A { 
    fn new() -> A; 
} 

struct B; 
impl A for B { 
    fn new() -> A { 
     B as A 
    } 
} 

fn main() { 
    println!("message") 
} 
<anon>:8:10: 8:16 error: cast to unsized type: `B` as `A` 
<anon>:8   B as A 
        ^~~~~~ 
<anon>:8:10: 8:11 help: consider using a box or reference as appropriate 
<anon>:8   B as A 
       ^
<anon>:7:20: 7:21 error: the trait `core::marker::Sized` is not implemented for the type `A + 'static` [E0277] 
<anon>:7  fn new() -> A { 
          ^
<anon>:7:20: 7:21 note: `A + 'static` does not have a constant size known at compile-time 
<anon>:7  fn new() -> A { 
          ^
error: aborting due to 2 previous errors 
playpen: application terminated with error code 101 
+0

Non completamente sicuro di quello che stai cercando, ma cambia la tua seconda linea in 'fn new() -> Self; 'fai quello che vuoi? – fjh

+0

Sì. Funziona davvero. E fa quello che volevo. Potresti rispondere e lo accetto? – 6D65

+0

Si noti che lo stile Rust è un rientro di 4 spazi. – Shepmaster

risposta

8

È necessario utilizzare il tipo di Self. Nelle dichiarazioni tratto, Self si riferisce al tipo che implementa un tratto. Nel tuo caso, la dichiarazione tratto dovrebbe apparire come segue:

trait A { 
    fn new() -> Self; // Self stands for any type implementing A 
} 

La versione originale è sottilmente diverso perché restituirà un trait object, non un valore del tipo implementor.

Problemi correlati