我將在 Haskell 編程后開始學習 Rust。該trait關鍵字感興趣,但是我我注意到你,只能是指一個型別(Self)。
在 Haskell 中,這種行為有一個編譯指示:
{-# LANGUAGE MultiParamTypeClasses #-}
class ExampleBehaviour a b where
combine :: a -> a -> b
co_combine :: b -> b -> a
但是,我看不到在 Rust 中有機地實作這種行為的方法。
uj5u.com熱心網友回復:
我認為這就是你要找的:
trait ExampleBehaviour<Other> {
fn combine(x: Other, y: Other) -> Self;
fn co_combine(x: Self, y: Self) -> Other;
}
這是該型別類的 Haskell 實體和 trait 的相應 Rust 實作的示例:
data Foo = Foo Int Int
newtype Bar = Bar Int
instance ExampleBehaviour Foo Bar where
combine (Foo x1 y1) (Foo x2 y2) = Bar (x1 * x2 y1 * y2)
co_combine (Bar x) (Bar y) = Foo x y
struct Foo(i32, i32);
struct Bar(i32);
impl ExampleBehaviour<Foo> for Bar {
fn combine(Foo(x1, y1): Foo, Foo(x2, y2): Foo) -> Self {
Bar(x1 * x2 y1 * y2)
}
fn co_combine(Bar(x): Self, Bar(y): Self) -> Foo {
Foo(x, y)
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/316825.html
上一篇:查找最頻繁元素的函式
