MST

星途 面试题库

面试题:Rust结构体方法设计之基础方法实现

假设有一个Rust结构体 `Rectangle`,包含两个字段 `width` 和 `height`,类型都是 `u32`。请为 `Rectangle` 结构体实现一个方法 `area`,用于计算矩形的面积并返回。同时,实现一个方法 `can_hold`,该方法接受另一个 `Rectangle` 实例作为参数,判断当前矩形是否能容纳传入的矩形(即当前矩形的宽和高都大于传入矩形的宽和高),并返回 `bool` 类型结果。
43.3万 热度难度
编程语言Rust

知识考点

AI 面试

面试题答案

一键面试
struct Rectangle {
    width: u32,
    height: u32,
}

impl Rectangle {
    fn area(&self) -> u32 {
        self.width * self.height
    }

    fn can_hold(&self, other: &Rectangle) -> bool {
        self.width > other.width && self.height > other.height
    }
}