面试题答案
一键面试// 定义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
函数通过条件判断返回对应描述,主函数进行测试。