struct Point {
x: i32,
y: i32,
}
// 第一个impl块,计算点到原点距离的方法
impl Point {
fn distance_to_origin(&self) -> f64 {
(self.x.pow(2) + self.y.pow(2)) as f64).sqrt()
}
}
// 第二个impl块,将点坐标翻倍的方法
impl Point {
fn double_coordinates(&mut self) {
self.x *= 2;
self.y *= 2;
}
}
// 复用相关功能的示例,通过trait
trait PointOps {
fn scale(&mut self, factor: i32);
}
impl PointOps for Point {
fn scale(&mut self, factor: i32) {
self.x *= factor;
self.y *= factor;
}
}
// 改进后的将点坐标翻倍的方法,复用trait中的功能
impl Point {
fn double_coordinates_using_trait(&mut self) {
self.scale(2);
}
}
- 第一个
impl
块:
- 实现了
distance_to_origin
方法,该方法使用勾股定理计算点到原点的距离,结果为f64
类型。
- 第二个
impl
块:
- 实现了
double_coordinates
方法,该方法直接修改结构体实例的x
和y
字段,将其翻倍。
- 复用相关功能:
- 定义了
PointOps
trait,其中有一个scale
方法,用于按给定因子缩放点的坐标。
- 为
Point
结构体实现了PointOps
trait。
- 在第二个
impl
块中可以定义新的方法double_coordinates_using_trait
,通过调用trait
中实现的scale
方法来复用相关功能,将点的坐标翻倍。