enum Command { Move(i32, i32), Attack, Rest, } fn apply_command<F>(mut x: i32, mut y:…
- User
enum Command { Move(i32, i32), Attack, Rest, }
fn apply_command(mut x: i32, mut y: i32, health: &mut i32, command: Command, mut action: F) where F: FnMut(&mut i32, &mut i32, &mut i32), { match command { Command::Move(dx, dy) => { x += dx; y += dy; } Command::Attack => { *health -= 10; } Command::Rest => { *health += 5; } }
code// 使用 closure 來進一步處理變更後的狀態 action(&mut x, &mut y, health);}
fn main() { let mut health = 100;
codelet commands = vec![ Command::Move(1, 0), Command::Attack, Command::Rest, Command::Move(0, 2), ]; for cmd in commands { apply_command(0, 0, &mut health, cmd, |x, y, hp| { println!("角色位置:({}, {}), 生命值:{}", x, y, hp); }); }} 請詳細說明
- Assistant
這段程式碼是用 Rust 語言實現的,目的是模擬一個角色(例如遊戲角色)在接受各種命令後的行為變化,包括移動、攻擊和休息,並基於這些變化來更新其位置與健康值。以下是對這段程式碼的逐步解析:
列舉類型
Commandrustenum Command { Move(i32, i32), Attack, Rest, }在這段代碼中,首先定義了一個列舉類型
Command,它有三種變體:Move(i32, i32):表示角色移動的命令,包含兩個整數參數,分別表示 x 和 y 軸的變化量。- :表示角色進行攻擊的命令。