Hi,
I recently hit a point where I go back and forth in between two implementations, changing it and returning to the other one quite frequently.
I am working with a slice of struct
holding two fields.
struct equation {
left: f64,
right: f64,
}
struct equations<'a> {
data: &'a [equation]
}
However, doing so is cumbersome for the implementation of the methods of the struct equations
as I am working only with the objects &[left]
and &[right]
.
The other possible implementation I used is directly:
struct equations<a'> {
left: &'a [f64],
right: &'a [f64],
}
Using this representation is way better in order to implement my methods, as I am working only either on the left
or the right
part, but never on both at the same time. However it makes it way less natural for the user (and myself) to create the objects, as it is not possible to create them one by one, it is only possible to create them once all of them are known.
I would like to be able to create an hybrid representation like the following one :
struct equation {
left: f64,
right: f64,
}
struct equations<a'> {
left: &'a [f64],
right: &'a [f64],
}
impl<'a> equations<'a> {
pub fn new(eqs: &'a [equation]) -> Self {
// Some magic there to create the two slices
}
}
I don't care much of the performance of the code (as it is only a pre-processing step before an expensive computation). I would just like to have the two slices so the code can be more efficient during the expensive computation.
I struggled has it is not possible to create a new reference in a function as it will go out of scope.
I found other posts discussing this topic (Struct as slice? and Returning a struct alongside a slice of one of its fields). There seams to be a solution using unsafe, but are the slices of [f64]
next to each other in memory? Also, would there be a way to do so with safe rust, knowing that the performance of this step does not matter, the sole purpose being to change the layout in memory so futures accesses are faster.
Thanks in advance !