2015-08-08 75 views
5

我試圖找到構造函數的特徵的例子,但沒有多少運氣。這是一個在Rust裏習慣的事情嗎?有沒有可能在特質中有構造函數?

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 

鑄造這將返回一個核心::標誌::大中相關的錯誤。

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

不完全確定你在找什麼,但是改變你的第二行爲'fn new() - > Self;'做你想做的事? – fjh

+0

是的。它確實有效。這種做我想做的。你可以請回復,我會接受嗎? – 6D65

+0

請注意,Rust風格是4格縮進。 – Shepmaster

回答

8

您需要使用Self類型。在特徵聲明中,Self是指實現特徵的類型。在你的情況,性狀聲明應如下所示:

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

您的原始版本略有不同,因爲它會返回一個trait object,而不是實現者類型的值。

相關問題