面试题答案
一键面试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);
}
- 引入
rand
库:在代码开头使用use rand::Rng;
引入rand
库中的Rng
trait,用于生成随机数。 - 模式匹配:在
match
表达式中,当value
是i32
类型时(通过v if v.is_i32()
进行类型判断),将其转换为i32
类型,生成随机bool
值,根据bool
值决定应用哪个闭包。 - 处理其他类型:对于非
i32
类型,使用panic!("Unsupported type")
抛出异常。
注意,在实际项目中,需要在Cargo.toml
文件中添加rand
依赖:
[dependencies]
rand = "0.8.5"
这里版本号可根据实际情况调整。