I have the following code:
#[derive(Clone, Copy)]
struct Point {
x: f64,
y: f64,
z: f64
}
impl Point {
fn set_z(&self, val: f64) -> Point {
Point{x: self.x, y: self.y, z: val}
}
}
struct Boo {
point: Point
}
impl Boo {
fn point(&self) -> &Point { &self.point }
fn set_point(&mut self, val: &Point) { self.point = *val; }
}
fn main() {
let mut boo = Boo{point:Point{x: 0., y: 0., z: 0.}};
let new_p = boo.point().set_z(17.);
boo.set_point(&new_p);
}
In fact, I have bunch of structures like Boo
with Point
fields, and often enough I need to change only one field in it.
So I can
Implement millions of methods like:
impl Boo { fn set_x(&mut self, val: f64) { self.point.x = val; } fn set_y(&mut self, val: f64) { self.point.y = val; } //... }
Which is too boring, and if have two, three fields like
point1
,point2
and so on I will be buried under tons of these methods.The method described at the top of the question looks nicer because I need only two methods per field, but I have to make modification in two steps: get point and set point.
So the ideal method for me would look like this:
boo.set_point(boo.point().set_z(17.));
But this is impossible, because to implement this I need to somehow read and write references at the same time.
How can I simplify setting only one field of Point
for users of my module?