I defined the following structs
and methods:
struct DataVar<'a> {
name: &'a str,
val: &'a [f64],
}
impl<'a> DataVar<'a> {
fn new(name: &'a str, val: &'a [f64]) -> Self {
Self { name, val }
}
}
struct DataSet<'a> {
name: &'a str,
datavars: &'a [&'a DataVar<'a>],
}
impl<'a> DataSet<'a> {
pub fn new(name: &'a str, datavars: &'a [&DataVar]) -> Self {
Self { name, datavars }
}
}
struct DataGroup<'a> {
name: &'a str,
datasets: &'a [&'a DataSet<'a>],
}
impl<'a> DataGroup<'a> {
fn new(name: &'a str, datasets: &'a [&DataSet]) -> Self {
Self { name, datasets }
}
}
Now the following code works:
let x = DataVar {
name: "X",
val: &[1., 2., 3.],
};
let dataset = DataSet {
name: "dataset",
datavars: &[&x, &x, &x],
};
let dataplot = DataGroup {
name: "datagroup",
datasets: &[&dataset, &dataset],
};
while the following does not work (I get the error "borrowed value does not live long enough" when defining dataplot
):
let x = DataVar::new("X", &[1., 2., 3.]);
let dataset = DataSet::new("dataset", &[&x, &x, &x]);
let dataplot = DataGroup::new("datagroup", &[&dataset, &dataset]);
Can this error be fixed with lifetimes parameters, or am I forced to define intermediate variables like let y = &[&x, &x, &x]
? I would like all references to live like x
, but cannot find out how to specify it with lifetime parameters.