Hi everyone! I read the forum basically every day, trying to learn new things. Thanks for a great and engaging community. I think I've nailed the basics of Rust, but am now starting to scratch the surface of Lifetimes.
Anyway.
I am trying to write a test help function that takes a Fn that borrows a field, and then returns a clone, for convenience. But the borrow checker is not having any of it!
#[test]
fn timestap_deserialize_serialize() -> Result<(), Box<dyn Error>> {
let date_str = "2021-01-02T12:53:39.392Z";
let mut value_to_deserialize = DatastoreValue::empty();
value_to_deserialize.timestamp_value = Some(date_str.to_string());
let date_time = NaiveDateTime::deserialize(value_to_deserialize)?;
let serialized_value: String =
get_datastore_value(date_time, |d| d.0.timestamp_value.as_ref())?;
assert_eq!(date_str, serialized_value);
Ok(())
}
fn get_datastore_value<'a, T, F>(
serializable: impl Serialize,
select_prop: F,
) -> Result<T, Box<dyn Error>>
where
T: 'a + Clone,
F: Fn(&'a DatastoreValue) -> Option<&'a T>,
{
match serializable.serialize()? {
None => return Err(Box::new(TestError::Unknown)),
Some(serialized_value) => {
let selected_prop = select_prop(&serialized_value);
match selected_prop {
None => return Err(Box::new(TestError::Unknown)),
Some(serialized_value_2) => Ok(serialized_value_2.clone()),
}
}
}
}
I think that my problem is that the 'a
in T: 'a + Clone
requires T
to obey the lifetime of 'a
even though i clone
it?
I know I can solve it by removing all the lifetimes and just moving out of the closure, but I wanted to learn more about borrowing.
Is it possible to "fix" get_datastore_value
and still keep borrowing?
Here is the error message:
error[E0597]: `serialized_value` does not live long enough
--> tests/entity/main.rs:140:45
|
129 | fn get_datastore_value<'a, T, F>(
| -- lifetime `'a` defined here
...
140 | let selected_prop = select_prop(&serialized_value);
| ------------^^^^^^^^^^^^^^^^^-
| | |
| | borrowed value does not live long enough
| argument requires that `serialized_value` is borrowed for `'a`
...
145 | }
| - `serialized_value` dropped here while still borrowed
Thanks!