MST

星途 面试题库

面试题:Rust中Option类型的基本使用与匹配

请编写一段Rust代码,定义一个函数,该函数接受一个i32类型的参数。如果参数大于10,返回Some(参数值的平方);否则返回None。然后在主函数中调用该函数,并通过match语句处理返回的Option值并打印结果。
10.6万 热度难度
编程语言Rust

知识考点

AI 面试

面试题答案

一键面试
fn square_if_greater_than_10(num: i32) -> Option<i32> {
    if num > 10 {
        Some(num * num)
    } else {
        None
    }
}

fn main() {
    let result = square_if_greater_than_10(15);
    match result {
        Some(squared) => println!("The square of the number is: {}", squared),
        None => println!("The number is not greater than 10"),
    }
}