面试题答案
一键面试use std::fmt::Debug;
use std::ops::Sub;
// 定义Point2D结构体
#[derive(Debug)]
struct Point2D {
x: f64,
y: f64,
}
// 定义Point3D结构体
#[derive(Debug)]
struct Point3D {
x: f64,
y: f64,
z: f64,
}
// 为Point2D实现Sub trait
impl Sub for Point2D {
type Output = Point2D;
fn sub(self, other: Point2D) -> Point2D {
Point2D {
x: self.x - other.x,
y: self.y - other.y,
}
}
}
// 为Point3D实现Sub trait
impl Sub for Point3D {
type Output = Point3D;
fn sub(self, other: Point3D) -> Point3D {
Point3D {
x: self.x - other.x,
y: self.y - other.y,
z: self.z - other.z,
}
}
}
// 定义一个通用的距离计算函数
fn distance<T>(point: &T, other: &T) -> f64
where
T: Sub<Output = T> + Debug,
T: std::ops::Mul<Output = T>,
T: std::convert::From<f64>,
{
let diff = point - other;
let sum_of_squares: f64 = diff.x * diff.x + diff.y * diff.y;
sum_of_squares.sqrt()
}
// 计算二维空间两点间距离
fn distance_2d(point1: &Point2D, point2: &Point2D) -> f64 {
distance(point1, point2)
}
// 计算三维空间两点间距离
fn distance_3d(point1: &Point3D, point2: &Point3D) -> f64 {
let diff = point1 - point2;
let sum_of_squares: f64 = diff.x * diff.x + diff.y * diff.y + diff.z * diff.z;
sum_of_squares.sqrt()
}
你可以这样调用这些函数:
fn main() {
let point2d_1 = Point2D { x: 0.0, y: 0.0 };
let point2d_2 = Point2D { x: 3.0, y: 4.0 };
let dist_2d = distance_2d(&point2d_1, &point2d_2);
println!("2D distance: {}", dist_2d);
let point3d_1 = Point3D { x: 0.0, y: 0.0, z: 0.0 };
let point3d_2 = Point3D { x: 3.0, y: 4.0, z: 12.0 };
let dist_3d = distance_3d(&point3d_1, &point3d_2);
println!("3D distance: {}", dist_3d);
}