我有以下代码:
#[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);
}
实际上,我有很多像Boo
这样的结构体,其中包含Point
字段,通常我只需要更改其中一个字段。
因此,我可以
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.
boo.set_point(boo.point().set_z(17.));
但这是不可能的,因为要实现这个目标,我需要同时读取和写入引用。
我如何简化我的模块用户设置Point
中仅有一个字段的操作?
impl Point { fn set_z(&self, val: f64) -> Point { Point{z: val, *self} } }
- S.R