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