MST
星途 面试题库

面试题:Rust结构体中panic处理的基础策略

在Rust结构体中,如果某个方法可能会因为不符合预期的输入导致panic,简述至少两种常规的处理策略,并举例说明。
19.8万 热度难度
编程语言Rust

知识考点

AI 面试

面试题答案

一键面试
  1. 使用Result类型处理错误
    • 策略简述:通过返回Result类型来表示操作可能成功或失败,而不是直接panic。这样调用者可以根据返回结果进行相应处理,而不是程序直接崩溃。
    • 示例代码
struct Rectangle {
    width: u32,
    height: u32,
}

impl Rectangle {
    fn new(width: u32, height: u32) -> Result<Rectangle, &'static str> {
        if width == 0 || height == 0 {
            Err("Width and height cannot be zero")
        } else {
            Ok(Rectangle { width, height })
        }
    }

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

fn main() {
    let rect1 = Rectangle::new(5, 10);
    match rect1 {
        Ok(rect) => println!("Area of rectangle: {}", rect.area()),
        Err(e) => println!("Error: {}", e),
    }
    let rect2 = Rectangle::new(0, 10);
    match rect2 {
        Ok(rect) => println!("Area of rectangle: {}", rect.area()),
        Err(e) => println!("Error: {}", e),
    }
}
  1. 使用Option类型处理可能的无效状态
    • 策略简述:当某个值可能不存在或处于无效状态时,使用Option类型。Some(T)表示存在有效数据,None表示无效状态。调用者可以通过模式匹配等方式来处理这两种情况,避免panic
    • 示例代码
struct User {
    username: String,
    age: Option<u32>,
}

impl User {
    fn new(username: String, age: Option<u32>) -> User {
        User { username, age }
    }

    fn display_info(&self) {
        println!("Username: {}", self.username);
        match self.age {
            Some(age) => println!("Age: {}", age),
            None => println!("Age not provided"),
        }
    }
}

fn main() {
    let user1 = User::new("Alice".to_string(), Some(30));
    user1.display_info();
    let user2 = User::new("Bob".to_string(), None);
    user2.display_info();
}