MST

星途 面试题库

面试题:Rust中如何通过函数实现代码复用并处理不同类型数据

在Rust中,假设有两个结构体`Point2D`和`Point3D`,分别表示二维和三维空间的点。请编写两个函数`distance_2d`和`distance_3d`计算两点间距离,并尽可能复用代码。`Point2D`包含`x`和`y`字段,`Point3D`包含`x`、`y`和`z`字段。
29.4万 热度难度
编程语言Rust

知识考点

AI 面试

面试题答案

一键面试
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);
}