簡體   English   中英

Rust 具有類型限制的特征

[英]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。

有兩個用例:

  1. 我可以使用一些任意類型,它知道如何在我的 Database::get(k: Keyable) function 中返回一個 key(),然后返回一些 Item(可能不僅僅是 key()。
  2. 在我的 fn Database::upsert() function 中,我希望能夠使用該項目至少是 Keyable 的事實,因此訪問 key() 來查找數據庫以決定我是簡單地插入還是更新。

您可以在關聯類型上放置特征綁定:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM