MST
星途 面试题库

面试题:Rust中复合数据类型嵌套的基础使用

请编写一个Rust程序,定义一个结构体`Point`表示二维坐标,包含`x`和`y`字段。再定义一个结构体`Rectangle`,它包含两个`Point`类型的字段,分别表示矩形的左上角和右下角坐标。实现一个函数,该函数接收一个`Rectangle`实例,计算并返回矩形的面积。
14.5万 热度难度
编程语言Rust

知识考点

AI 面试

面试题答案

一键面试
struct Point {
    x: f64,
    y: f64,
}

struct Rectangle {
    top_left: Point,
    bottom_right: Point,
}

fn calculate_area(rect: &Rectangle) -> f64 {
    let width = rect.bottom_right.x - rect.top_left.x;
    let height = rect.top_left.y - rect.bottom_right.y;
    width * height
}