I am trying to split a string into several parts and store everything in the same struct and I would like to do so without cloning anything.
This is roughly what I have:
Struct:
pub struct PkgName<'a> {
pub fname: String,
pub name: &'a str,
pub ver: &'a str,
}
Impl (minus lifetime params):
impl PkgName {
//the String move is intended, to avoid cloning
fn parse(fname: String) -> PkgName {
let end_name: usize = /* .... */;
let name = &fname[..end_name];
let ver = &fname[end_name+1..];
PkgName {fname, name, ver}
}
}
I already tried with several combinations of lifetime parameters, to no avail.
Example of desired result:
PkgName {
fname: "archlinux-keyring-20170823-1",
name: "archlinux-keyring",
ver: "20170823-1"
}
Again: name
and ver
must be slices of fname
.
Edit:
After reading the duplicate: Why can't I store a value and a reference to that value in the same struct?
I propose an alternative solution that would involve unsafe code: a new type should store the offset between the fields (target - source) plus an additional offset such that it points to the beginning of the desired string; also it should store the size. It basically still behaves like a reference, so it should implement Deref
.
As only offsets are saved in this new type, this is move-safe although, of course, only should apply to immutable fields.