Rust借用检查器报错求助:导弹数量更新与命令获取问题
Rust导弹发射代码问题排查与修复
核心问题分析
1. 借用检查器报错原因
- 原代码中
command = &mut command_str.trim();存在两处错误:trim()返回的是不可变引用(&str),无法强制转为可变引用&mut str;即使去掉&mut,command持有command_str的引用后,后续调用get_general_command()修改command_str会导致引用悬空,违反Rust的借用规则。 - 闭包捕获变量时的所有权和引用关系处理不当,导致编译器拒绝通过。
2. 剩余导弹数量不更新
red_button闭包接收的是missiles的值拷贝,内部修改的new_missiles无法同步到外部变量。- 闭包内错误打印原
missiles值,而非更新后的剩余数量。
3. 用户命令逻辑缺陷
- 仅初始化时读取一次输入,循环内用户输入错误后未重新解析命令。
- 循环条件依赖
missiles值,但missiles从未被更新,导致逻辑异常。
修复后的完整代码
// Silence some warnings so they don't distract from the exercise. // #![allow(unused_variables)] // use standard library (allows me to get user input) use std::io; const MISSILE_PARAM: (i32, i32) = (8, 2); // Using different variables fn fire_in_the_hole(){ let (mut missiles, ready) = MISSILE_PARAM; let mut command_str = String::new(); // 发射导弹逻辑:返回剩余导弹数量 let red_button = |current_missiles: i32| -> i32 { let remaining = current_missiles - ready; println!("Firing {} of my {} missiles...", ready, current_missiles); println!("{} missiles left", remaining); remaining }; // 获取用户命令:返回修剪后的字符串,避免引用问题 let mut get_general_command = || -> String { command_str.clear(); // 清空旧输入 io::stdin() .read_line(&mut command_str) .expect("Failed to read command!"); command_str.trim().to_string() }; println!("FIRE IN THE HOLE!!!"); missiles = red_button(missiles); println!("Fire again? [Y/N]"); // 循环处理用户命令 while missiles >= ready { let command = get_general_command(); match command.as_str() { "Y" | "y" => { missiles = red_button(missiles); println!("Fire again? [Y/N]"); }, "N" | "n" => { println!("Gotcha, General. We've got {} missiles left for next time.", missiles); break; }, _ => println!("That's not a real command, General! Please try again. [Y/N]"), } } println!("All out of ammo, General."); } // Calculate the area fn area_of(x: i32, y: i32) -> i32 { x*y } // Calculate the volume fn volume_of(a: i32, b: i32, c: i32) -> i32 { a*b*c } fn main() { let width = 4; let height = 7; let depth = 10; let area = area_of(width, height); println!("Area is {}", area); let volume = volume_of(width, height, depth); println!("Volume is {}", volume); // 调用导弹发射逻辑 fire_in_the_hole(); }
关键修改说明
- 解决借用冲突:将
get_general_command改为返回String(所有权转移),避免使用引用;每次读取前清空command_str防止旧输入残留。 - 同步导弹数量:
red_button闭包返回更新后的剩余导弹数,外部通过赋值同步状态。 - 修复命令逻辑:每次循环重新读取命令,用
match简化判断,覆盖所有输入场景。 - 优化循环条件:用
ready常量代替硬编码的2,保持代码一致性。 - 补充函数调用:在
main中添加fire_in_the_hole()调用,确保导弹发射逻辑执行。
内容的提问来源于stack exchange,提问作者jdoh
相关产品推荐
相关产品推荐

