[英]Rust Traits with Type Bounds
I want to write a basic abstraction of a database, using Rust traits.我想使用 Rust 特征编写数据库的基本抽象。
pub trait Keyable {
type Key;
fn key(&self) -> &Self::Key;
}
and和
// 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>;
}
I am struggling to express this: Database::Item must be at least Keyable.我很难表达这一点:Database::Item 必须至少是 Keyable。
There are two use cases:有两个用例:
You can place a trait bound on an associated type:您可以在关联类型上放置特征绑定:
pub trait Database {
type Item: Keyable;
Then, you can use that trait's associated type(s) in function signatures:然后,您可以在 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>;
(I also added an &
because get()
probably shouldn't be required to consume the key data.) (我还添加了一个
&
因为get()
可能不需要使用关键数据。)
Putting that all together to a compilable example:将所有这些放在一个可编译的示例中:
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.