[英]Rust Traits with Type Bounds
我想使用 Rust 特征編寫數據庫的基本抽象。
pub trait Keyable {
type Key;
fn key(&self) -> &Self::Key;
}
和
// type alias for result - DbError are defined elsewhere
pub type Result<T> = Result<T, DbError>;
pub trait Database {
type Item;
fn get(&self, id: Keyable) -> Result<Self::Item>;
fn upsert(&self, item: Self::Item) -> Result<Keyable>;
}
我很難表達這一點:Database::Item 必須至少是 Keyable。
有兩個用例:
您可以在關聯類型上放置特征綁定:
pub trait Database {
type Item: Keyable;
然后,您可以在 function 簽名中使用該特征的關聯類型:
fn get(&self, id: &<Self::Item as Keyable>::Key) -> Result<Self::Item>;
fn upsert(&self, item: Self::Item) -> Result<<Self::Item as Keyable>::Key>;
(我還添加了一個&
因為get()
可能不需要使用關鍵數據。)
將所有這些放在一個可編譯的示例中:
pub enum DbError { Something }
pub type Result<T> = std::result::Result<T, DbError>;
pub trait Keyable {
type Key;
fn key(&self) -> &Self::Key;
}
pub trait Database {
type Item: Keyable;
fn get(&self, id: &<Self::Item as Keyable>::Key) -> Result<Self::Item>;
fn upsert(&self, item: Self::Item) -> Result<<Self::Item as Keyable>::Key>;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.