MST

星途 面试题库

面试题:Rust中复杂结构体的模式匹配解构

假设有如下Rust结构体定义: ```rust struct Point { x: i32, y: i32, } struct Rectangle { top_left: Point, bottom_right: Point, } ``` 请编写一段代码,使用模式匹配解构`Rectangle`结构体,获取`top_left`点的`x`坐标和`bottom_right`点的`y`坐标,并将它们相加返回。
41.2万 热度难度
编程语言Rust

知识考点

AI 面试

面试题答案

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

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

fn sum_coordinates(rect: Rectangle) -> i32 {
    match rect {
        Rectangle {
            top_left: Point { x: top_left_x, .. },
            bottom_right: Point { y: bottom_right_y, .. },
        } => top_left_x + bottom_right_y,
    }
}