RustのTrait
Haskellerなら型クラスとほぼ同じものと理解できる

型クラス制約のようなもの
継承
基本的な使用例
traitを定義する
rs// traitを定義
trait HogeTrait {
fn hoge_method() -> u32; // methodは本体を書かない
}
traitを実装する
Hoge
という型に HogeTrait
を実装する
rsimpl HogeTrait for Hoge {
fn hoge_method() {
42
}
}
参考
前半しか読んでない

traitから型を作る構文が2つある
具体的な型を隠蔽して、実装しているtraitだけに注目させる
時系列
Rust 1.26 (2018)
Rust 1.27 (2018)
dyn の明示が必須になった
dyn Traitの概念自体は最初からあったが、明示しないといけなくなった
Rust 2018 edition
Rustのトレイトは「高カインド多相のない型クラス」である
任意の型がサポートできる性質
既存の型に任意のメソッドを生やせる
str
や bool
とかにも。
overloadの類型だが、以下のような機能がありmixinやinterfaceのようなもの
メソッド呼び出し構文
Self型
関連付けられたmethod
関連関数
関連定数
マーカーとしての機能
型に対し実装すべきメソッドを定義したもの,
Haskellの型クラスと似ている部分が多い
型クラス、trait
型クラス制約、trait境界
default実装あり
継承あり
ad hoc多相
これhsでできたっけ?
derivingとか
例
生やしたmethodの名前衝突を避けるために、明示的にuseする必要がある
rslet mut buf: Vec<u8> = vec![];
buf.write_all(b"hello")?;
このmodule内で、 use std::io::Write;
を書いていないとエラーになる
Cloneとiteratorは例外で、useしなくても良い
defaultで暗黙にuseされている
自動導出
#[derive(Hoge)]
型定義時に自動で実装する
実装をわざわざ手で書かなくて済む
rs#[derive(Debug, Clone, PartialEq, Eq, Hash)]
struct Annot<T> {
value: T,
loc: Loc,
}
標準ライブラリで導出可能なもの
Clone
Copy
Debug
Default
Eq
Hash
Ord
PartialEq
PartialOrd
Haskell由来らしい
Self型
hsにそんなんあったっけ
普通に class Maybe s where
と書けば、 Self
な s
が決まるから、特に何も考えなくても良いか
関連付けられたmethod
Tour of Rust's Standard Library Traits
関連