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的慣用方式是什麼?
請製作[MCVE],您可以使用Rust Playground來做到這一點。您可能還想在Google上搜索您的錯誤消息,它已經在計算器上出現了很多次。 –
當前,您定義的'Injection'包含四個**靜態函數**。如果你想定義方法,你需要指定'self'參數。我會建議(重新)閱讀方法語法的章節:https://doc.rust-lang.org/book/second-edition/ch05-03-method-syntax.html –
通常,你不會有很容易試圖直接將Scala翻譯成Rust。通過解釋你正在努力達成的目標開始會容易得多。 –