MST

星途 面试题库

面试题:Rust枚举变体模式匹配在实际场景中的优化应用

在一个游戏开发场景中,有一个枚举 `enum PlayerAction { Move(i32, i32), Attack(String), Defend(i32) }`,表示玩家的不同动作。现在需要实现一个函数 `fn handle_player_action(action: PlayerAction)`,要求使用高效的模式匹配来处理这些动作。同时,假设在处理 `Attack` 动作时,需要根据攻击类型字符串判断是否为特殊攻击(例如 “special_attack”),如果是则对攻击力进行翻倍处理,并且要求对所有动作的处理都要记录到日志文件中。请写出完整的实现代码,并解释为什么这样实现能达到高效匹配与处理。
34.9万 热度难度
编程语言Rust

知识考点

AI 面试

面试题答案

一键面试
use std::fs::File;
use std::io::{Write, BufWriter};

enum PlayerAction {
    Move(i32, i32),
    Attack(String),
    Defend(i32)
}

fn handle_player_action(action: PlayerAction) {
    let log_file = File::create("game_log.txt").expect("Failed to create log file");
    let mut log_writer = BufWriter::new(log_file);

    match action {
        PlayerAction::Move(x, y) => {
            writeln!(log_writer, "Player moved to ({}, {})", x, y).expect("Failed to write to log");
            println!("Player moved to ({}, {})", x, y);
        },
        PlayerAction::Attack(attack_type) => {
            let attack_power = if attack_type == "special_attack" {
                200 // 假设特殊攻击攻击力翻倍为200
            } else {
                100 // 普通攻击攻击力为100
            };
            writeln!(log_writer, "Player attacked with type: {}, power: {}", attack_type, attack_power).expect("Failed to write to log");
            println!("Player attacked with type: {}, power: {}", attack_type, attack_power);
        },
        PlayerAction::Defend(power) => {
            writeln!(log_writer, "Player defended with power: {}", power).expect("Failed to write to log");
            println!("Player defended with power: {}", power);
        }
    }
}

高效匹配与处理的原因

  1. 模式匹配的高效性:Rust 的 match 语句采用了类似 switch - case 的高效匹配机制,在编译期会生成高效的跳转表(对于简单类型和枚举),所以匹配不同的 PlayerAction 变体时效率很高。
  2. 针对性处理:对于 Attack 动作,在匹配时直接判断攻击类型字符串,避免了额外的条件判断嵌套,代码逻辑清晰,提高了处理效率。
  3. 日志记录:在每个匹配分支中直接进行日志记录,保证了所有动作处理的即时记录,没有额外的性能开销。