Rust 添加绑定到借用类型

问题描述 投票:0回答:1

有没有办法借用类型并在内部类型上添加特征绑定(即您有类型 &T 但想要说出 T 的位置)

我假设我可以要求 &T 拥有 ToOwned,然后将约束添加到 Owned 类型,但这似乎保留了借用,例如在这个小例子中。为什么下面的方法不起作用,有没有办法获得内部类型?

let c: <&i32 as ToOwned>::Owned = 1;
//                                ^ expected &i32, found i32

我的最终目标是能够接受一种实现了diesel::Identifying的类型,并且该Identifying的Id必须实现Deserialize。目前我有一个这样的结构

#[derive(Queryable, Selectable, Identifiable, serde::Serialize, serde::Deserialize)]
#[diesel(table_name = crate::schema::my_models)]
#[diesel(check_for_backend(diesel::pg::Pg))]
pub struct MyDieselModel {
    pub id: i32,
    pub title: String,
    pub body: String,
    pub published: bool,
}

还有一个类似这样的函数:

fn use_model<'ident, T>(model: T)
where
    T: HasTable,
    &'ident T: Identifiable
    <&'ident TModel as Identifiable>::Id: Send + ToOwned,
    <<&'ident TModel as Identifiable>::Id as ToOwned>::Owned: Deserialize<'ident>,
{
   ...
}

如果我打电话

use_model<MyDieselModel>()
,它不会说

the trait bound `&i32: Deserialize<'_>` is not satisfied
the trait `Deserialize<'_>` is implemented for `i32`
for that trait implementation, expected `i32`, found `&i32`

考虑到上面的例子, ::Owned 没有给出借用中的类型,这是完全有意义的...关于如何实现这一点有什么想法吗?

rust traits borrow-checker bounds rust-diesel
1个回答
0
投票

请注意,

ToOwned
是为T
实现的,而不是为
&T
实现的。你可以通过
Deref::Target
实现你想要的:

use std::ops::Deref; fn main() { let _c: <&i32 as Deref>::Target = 1; }

游乐场

© www.soinside.com 2019 - 2024. All rights reserved.