MST

星途 面试题库

面试题:Rust中match表达式针对枚举类型的模式匹配应用

假设我们有如下枚举类型: ```rust enum TrafficLight { Red, Yellow, Green } ``` 请使用`match`表达式实现一个函数`traffic_light_action`,当输入为`TrafficLight::Red`时返回字符串`"Stop"`,`TrafficLight::Yellow`时返回`"Prepare to stop"`,`TrafficLight::Green`时返回`"Go"`。
44.6万 热度难度
编程语言Rust

知识考点

AI 面试

面试题答案

一键面试
enum TrafficLight {
    Red,
    Yellow,
    Green
}

fn traffic_light_action(light: TrafficLight) -> &'static str {
    match light {
        TrafficLight::Red => "Stop",
        TrafficLight::Yellow => "Prepare to stop",
        TrafficLight::Green => "Go"
    }
}