面试题答案
一键面试struct Point {
x: i32,
y: i32,
}
impl Point {
pub fn distance_from_origin(&self) -> f64 {
(self.x.pow(2) + self.y.pow(2)) as f64.sqrt()
}
// 私有方法
fn scale(&mut self, factor: i32) {
self.x *= factor;
self.y *= factor;
}
}
fn main() {
let mut p = Point { x: 3, y: 4 };
let dist = p.distance_from_origin();
println!("Distance from origin: {}", dist);
// 尝试调用私有方法,这会导致编译错误
// p.scale(2);
}
上述代码中:
- 定义了结构体
Point
包含两个i32
类型字段x
和y
。 - 在
impl
块中为Point
实现了distance_from_origin
公共方法用于计算到原点距离。 - 实现了私有方法
scale
用于缩放坐标,但在main
函数中无法直接调用私有方法。 - 在
main
函数中创建了Point
实例并调用了公共方法distance_from_origin
打印距离。