繁体   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