With jofas's help
I solved reading data from Redb problem
I got another challenge: saving data into redb
this is my saving function
(I have to set V
and KEY
with the same lifetime, because table.insert
needs the same lifetime args
pub(crate) fn write<'c, K, V, KEY, D>(table: TableDefinition<K, V>, key: KEY, value: &'c D) -> Result<()>
where
K: redb::RedbKey,
for<'a> V: redb::RedbValue<SelfType<'a> = &'a [u8]>,
for<'a> KEY: Borrow<&'a str> + std::borrow::Borrow<<K as redb::RedbValue>::SelfType<'a>>,
D: serde::Serialize,
{
match serde_json::to_vec(value) {
Ok(r) => {
let write_txn = DB.begin_write()?;
{
let mut table = write_txn.open_table(table)?;
table.insert(key.borrow(), r.as_slice())?;
}
write_txn.commit()?;
Ok(())
}
Err(e) => Err(Error::ErrorWithMessage(format!("{:?}", e))),
}
}
when I call this function
const SETTINGS_KEY: &str = "settings";
pub(crate) fn init() -> Result<()> {
let settings = Settings::default();
db::write(TABLE, SETTINGS_KEY, &settings)
}
I got this error
error: implementation of `Borrow` is not general enough
--> src\man\settings.rs:39:5
|
39 | db::write(TABLE, SETTINGS_KEY, &settings)
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ implementation of `Borrow` is not general enough
|
= note: `&'2 str` must implement `Borrow<&'1 str>`, for any lifetime `'1`...
= note: ...but it actually implements `Borrow<&'2 str>`, for some specific lifetime `'2`
I also tried this
pub(crate) fn write<'a, K, V, KEY, D>(table: TableDefinition<K, V>, key: KEY, value: &D) -> Result<()>
where
K: redb::RedbKey,
V: redb::RedbValue<SelfType<'a> = &'a [u8]>,
KEY: Borrow<&'a str> + std::borrow::Borrow<<K as redb::RedbValue>::SelfType<'a>>,
D: serde::Serialize,
{
let d = serde_json::to_vec(value)?;
let vv = d.as_slice();
let write_txn = DB.begin_write()?;
{
let mut table = write_txn.open_table(table)?;
table.insert(key, vv)?;
}
write_txn.commit()?;
Ok(())
}
Still failed with
error[E0597]: `d` does not live long enough
--> src\db\mod.rs:248:14
|
239 | pub(crate) fn write<'a, K, V, KEY, D>(table: TableDefinition<K, V>, key: KEY, value: &D) -> Result<()>
| -- lifetime `'a` defined here
...
247 | let d = serde_json::to_vec(value)?;
| - binding `d` declared here
248 | let vv = d.as_slice();
| ^^^^^^^^^^^^ borrowed value does not live long enough
...
253 | table.insert(key, vv)?;
| --------------------- argument requires that `d` is borrowed for `'a`
...
264 | }
| - `d` dropped here while still borrowed
I got what compiler said, the 'a
will last whole process call, but d
dropped at the end of the function
but I didn't understand that this line table.insert(key, vv)?;
, vv had finished its job, why needs to be last as long as 'a
Thanks in advance