MST

星途 面试题库

面试题:Rust枚举类型在函数参数与返回值中的模式匹配应用

定义一个函数 `handle_direction`,其参数为一个枚举类型 `Direction`,该枚举有 `North`、`South`、`East`、`West` 四个变体。函数通过模式匹配,根据不同的方向变体返回相应的字符串描述(例如,`North` 返回 "Move forward to the north")。接着,在主函数中调用该函数,并传入不同的 `Direction` 枚举值进行测试。
16.8万 热度难度
编程语言Rust

知识考点

AI 面试

面试题答案

一键面试
// 定义Direction枚举
enum Direction {
    North,
    South,
    East,
    West,
}

// 定义handle_direction函数
fn handle_direction(dir: Direction) -> &'static str {
    match dir {
        Direction::North => "Move forward to the north",
        Direction::South => "Move forward to the south",
        Direction::East => "Move forward to the east",
        Direction::West => "Move forward to the west",
    }
}

fn main() {
    let north_desc = handle_direction(Direction::North);
    let south_desc = handle_direction(Direction::South);
    let east_desc = handle_direction(Direction::East);
    let west_desc = handle_direction(Direction::West);

    println!("North description: {}", north_desc);
    println!("South description: {}", south_desc);
    println!("East description: {}", east_desc);
    println!("West description: {}", west_desc);
}

上述代码使用Rust语言实现,定义了Direction枚举,handle_direction函数通过模式匹配返回对应方向的字符串描述,主函数中调用该函数并传入不同枚举值进行测试。

如果使用Python,可如下实现:

from enum import Enum


class Direction(Enum):
    North = 1
    South = 2
    East = 3
    West = 4


def handle_direction(dir):
    if dir == Direction.North:
        return "Move forward to the north"
    elif dir == Direction.South:
        return "Move forward to the south"
    elif dir == Direction.East:
        return "Move forward to the east"
    elif dir == Direction.West:
        return "Move forward to the west"


if __name__ == "__main__":
    north_desc = handle_direction(Direction.North)
    south_desc = handle_direction(Direction.South)
    east_desc = handle_direction(Direction.East)
    west_desc = handle_direction(Direction.West)

    print(f"North description: {north_desc}")
    print(f"South description: {south_desc}")
    print(f"East description: {east_desc}")
    print(f"West description: {west_desc}")

Python代码通过enum模块定义Direction枚举,handle_direction函数通过条件判断返回对应描述,主函数进行测试。