2017-09-11 73 views
0

我有困難的轉換這斯卡拉特質生鏽如何將斯卡拉匿名特質實現轉換爲Rust?

trait Inject[A, B] { 
    self => 

    def inject(input: A): B 

    def project(input: B): Try[A] 

    def contraMap[AA](inj: Inject[AA, A]): Inject[AA, B] = new Inject[AA, B] { 
    override def inject(input: AA) = self.inject(inj.inject(input)) 

    override def project(input: B) = self.project(input).flatMap(i => inj.project(i)) 
    } 

    def map[BB](inj: Inject[B, BB]): Inject[A, BB] = new Inject[A, BB] { 
    override def inject(input: A) = inj.inject(self.inject(input)) 

    override def project(input: BB) = inj.project(input).flatMap(i => self.project(i)) 
    } 

} 

這裏是我的防鏽相當於

pub trait Injection<A, B> { 
    fn inject(input: A) -> B; 
    fn project(input: B) -> Result<A, InjectionError>; 
    fn contraMap<AA>(input: Injection<AA, A>) -> Injection<AA, B>; 
    fn map<BB>(input: Injection<B, BB>) -> Injection<A, BB>; 
} 

pub struct InjectionError { 
    msg: String, 
} 

我越來越:

error[E0038]: the trait `Injection` cannot be made into an object 
--> src/main.rs:4:5 
    | 
4 |  fn contraMap<AA>(input: Injection<AA, A>) -> Injection<AA, B>; 
    |  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `Injection` cannot be made into an object 
    | 
    = note: method `inject` has no receiver 
    = note: method `project` has no receiver 
    = note: method `contraMap` has no receiver 
    = note: method `map` has no receiver 

如果我添加一個self參考,我仍然得到相同的錯誤:

pub trait Injection<A, B> { 
    fn inject(&self, input: A) -> B; 
    fn project(&self, input: B) -> Result<A, InjectionError>; 
    fn contraMap<AA>(&self, input: Injection<AA, A>) -> Injection<AA, B>; 
    fn map<BB>(&self, input: Injection<B, BB>) -> Injection<A, BB>; 
} 

pub struct InjectionError { 
    msg: String, 
} 

我不知道如何實例化一個匿名Injection就像我在Scala中做的那樣。將Scala特徵轉換爲Rust的慣用方式是什麼?

+2

請製作[MCVE],您可以使用Rust Playground來做到這一點。您可能還想在Google上搜索您的錯誤消息,它已經在計算器上出現了很多次。 –

+1

當前,您定義的'Injection'包含四個**靜態函數**。如果你想定義方法,你需要指定'self'參數。我會建議(重新)閱讀方法語法的章節:https://doc.rust-lang.org/book/second-edition/ch05-03-method-syntax.html –

+2

通常,你不會有很容易試圖直接將Scala翻譯成Rust。通過解釋你正在努力達成的目標開始會容易得多。 –

回答

0

在鏽中,性狀只描述行爲,而不描述數據。編譯器告訴你,你的特徵不是對象安全的,因爲你想要返回實現特徵的任何東西,而且在編譯時這個「任何東西」沒有單一規範的已知大小。

你可以Box把你的價值放在堆上,或者使用引用(這將需要一些可怕的終生雜耍,並且相當脆弱,但是避免分配)。您還需要返回mapcontraMap的具體類型。查看Rust的Iterator特徵如何實現它:它返回一個Map,它在原始迭代器和它映射的函數類型上是泛型的,包裝並實現Iterator