I have a struct defined like
struct Foo<'a> {
field1: &'a str,
field2: &'a str,
field3: &'a u8,
// ...
}
that I use for returning parsing results from an mmap
ped file. For some successful parses, I want to store the results for later processing and for various reasons that processing will happen after the memory is released. I could do something like
struct OwnedFoo {
field1: String,
field2: String,
field3: Vec<u8>,
// ...
}
and manually converting all Foo
s that I'm interested in into OwnedFoos
. However I'm wondering if I could do something like:
struct Foo<'a> {
field1: Cow<'a, str>,
field2: Cow<'a, str>,
field3: Cow<'a, u8>,
...
}
instead and if there's any way to automatically make all the Cow
s owned and erase the lifetime parameter. I haven't found anything in the library documentation that seems applicable.
Something like:
let a = Foo { ... };
let a_owned = a.into_owned();
// do stuff with a_owned that I can't do with a
Building blocks:
Cow::into_owned
will return the owned version.'static
is the lifetime of the programTherefore we can write a utility function:
use std::borrow::Cow;
fn into_owned<'a, B>(c: Cow<'a, B>) -> Cow<'static, B>
where B: 'a + ToOwned + ?Sized
{
Cow::Owned(c.into_owned())
}
You can expand this to Foo<'a>
becoming Foo<'static>
by simply applying the transformation on all fields.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With