MST

星途 面试题库

面试题:Rust match表达式的高级模式匹配与闭包结合应用

假设有以下结构体和闭包定义: ```rust struct Container<T> { value: T } let add_five: fn(i32) -> i32 = |x| x + 5; let multiply_by_two: fn(i32) -> i32 = |x| x * 2; ``` 使用`match`表达式对`Container`进行模式匹配,当`Container`中的`value`是`i32`类型时,根据一个随机生成的`bool`值(假设使用`rand::random::<bool>()`生成),如果为`true`,应用`add_five`闭包到`value`上;如果为`false`,应用`multiply_by_two`闭包到`value`上,最后返回结果。请完善代码实现该功能。注意要处理好`rand`库的引入等细节。
23.1万 热度难度
编程语言Rust

知识考点

AI 面试

面试题答案

一键面试
use rand::Rng;

struct Container<T> {
    value: T
}

fn main() {
    let add_five: fn(i32) -> i32 = |x| x + 5;
    let multiply_by_two: fn(i32) -> i32 = |x| x * 2;

    let container = Container { value: 10_i32 };

    let result = match container.value {
        v if v.is_i32() => {
            let num = v as i32;
            let random_bool = rand::thread_rng().gen::<bool>();
            if random_bool {
                add_five(num)
            } else {
                multiply_by_two(num)
            }
        },
        _ => panic!("Unsupported type")
    };

    println!("Result: {}", result);
}
  1. 引入rand:在代码开头使用use rand::Rng;引入rand库中的Rng trait,用于生成随机数。
  2. 模式匹配:在match表达式中,当valuei32类型时(通过v if v.is_i32()进行类型判断),将其转换为i32类型,生成随机bool值,根据bool值决定应用哪个闭包。
  3. 处理其他类型:对于非i32类型,使用panic!("Unsupported type")抛出异常。

注意,在实际项目中,需要在Cargo.toml文件中添加rand依赖:

[dependencies]
rand = "0.8.5"

这里版本号可根据实际情况调整。