Rust 特征与类型限制
我想使用 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 的。
有两个用例:
- 我可以使用一些任意类型,它知道如何在我的 Database::get(k: Keyable) 函数中返回 key() ,但返回一些 Item (这可能不仅仅是 在我的 fn Database::upsert( )
- 函数中,我希望能够使用该项目至少是 Keyable 的事实,因此如果我只是简单地访问 key() 来查找数据库以做出决定插入或更新。
I want to write a basic abstraction of a database, using Rust traits.
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.
There are two use cases:
- I can use some arbitrary type which knows how to return a key() in my Database::get(k: Keyable) function and yet return some Item (which is likely to have quite a bit more than just the key().
- In my fn Database::upsert() function, I want to be able to use the fact that the item is at least Keyable and therefore access the key() to lookup the database to make a decision if I simply insert or update.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以在关联类型上放置特征绑定:
然后,您可以在函数签名中使用该特征的关联类型:(
我还添加了
&
因为get() 可能不需要使用关键数据。)
将它们全部放在一个可编译的示例中:
You can place a trait bound on an associated type:
Then, you can use that trait's associated type(s) in function signatures:
(I also added an
&
becauseget()
probably shouldn't be required to consume the key data.)Putting that all together to a compilable example: