当在 gtk 条目中按下 Enter 键时,我正在尝试使用 Diesel 从数据库中获取对象。我的想法是在 main 函数中创建一个 Diesel SQLite 连接,然后在每次需要时借用它。
为此,我正在尝试使用一个非常简单的 MVC。这个想法是将连接传递给所有控制器并重用它。我知道这里需要一生。
pub struct Controller<'a> {
pub connection: &'a SQLiteConnection,
pub search_entry: SearchEntry,
....
}
impl<'a> Controller<'a> {
pub fn new(conn: &'a SQLiteConnection) -> Self {
Self {
search_entry: SearchEntry::new(),
connection: conn,
....
}
}
pub fn init(&self) {
self.search_entry.connect_activate(|x| {
let need_it = diesel_table
.filter(column_id.eq(&x.get_text().unwrap()))
.first(self.connection)
.unwrap();
});
}
}
编译时我得到这个:
error[E0495]: cannot infer an appropriate lifetime due to conflicting requirements
--> src/lib.rs:44:44
|
44 | self.search_entry.connect_activate(|x| {
| ____________________________________________^
45 | | let need_it = diesel_table
46 | | .filter(column_id.eq(&x.get_text().unwrap()))
47 | | .first(self.connection)
48 | | .unwrap();
49 | | });
| |_________^
|
note: first, the lifetime cannot outlive the anonymous lifetime #1 defined on the method body at 43:5...
--> src/lib.rs:43:5
|
43 | / pub fn init(&self) {
44 | | let need_it = diesel_table
46 | | .filter(column_id.eq(&x.get_text().unwrap()))
47 | | .first(self.connection)
48 | | .unwrap();
49 | | });
50 | | }
| |_____^
note: ...so that the types are compatible
--> src/lib.rs:44:44
|
44 | self.search_entry.connect_activate(|x| {
| ____________________________________________^
45 | | let need_it = diesel_table
46 | | .filter(column_id.eq(&x.get_text().unwrap()))
47 | | .first(self.connection)
48 | | .unwrap();
49 | | });
| |_________^
= note: expected `&&Controller<'_>`
found `&&Controller<'a>`
= note: but, the lifetime must be valid for the static lifetime...
note: ...so that the type `[closure@src/lib.rs:44:44: 49:10 self:&&Controller<'_>]` will meet its required lifetime bounds
--> src/lib.rs:44:27
|
44 | self.search_entry.connect_activate(|x| {
| ^^^^^^^^^^^^^^^^
这个错误是因为函数connect_activate
有一个静态参数:fn connect_activate<F: Fn(&Self) + 'static>
.
我不想在用户每次按下 Intro 键时使用返回连接的函数来初始化连接。相反,我想借用这种联系。
最有效的方法是什么?
非常感谢你。我希望你明白一切。