You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rust中输入已移除Vec元素的错误处理方案咨询

解决Rust猜数字游戏重复输入导致的Panic问题

你的问题出在两个核心点:

  • choices.iter().position(|x| *x == guess)返回的是Option<usize>,而非Result类型,所以不能用Ok/Err匹配,对应分支应为Some/None
  • 直接调用unwrap()会在结果为None时触发panic,必须显式处理这种无效输入场景

正确的错误处理方式是对position的返回值做Option匹配,判断输入数字是否还在可选列表中:

use std::io;
use std::cmp::Ordering;
use rand::Rng;
use owo_colors::{OwoColorize, colors::{CustomColor}};
pub fn main() {
    println!("{}", "Please Guess (1-5)😀".magenta());
    let random = rand::thread_rng().gen_range(1..=5);
    let mut choices = vec![1,2,3,4,5];
  
    loop {
        let mut guess = String::new();
        io::stdin().read_line(&mut guess).expect("Failed to read line");    
        let guess: usize = match guess.trim().parse() {
            Ok(number) => number,
            Err(error) => { 
                println!("{}", error); 
                continue;
            }
        };
        
        // 处理数字已被移除的情况
        let index = match choices.iter().position(|x| *x == guess) {
            Some(idx) => idx,
            None => {
                println!("You already guessed this number! Try another one.");
                continue;
            }
        };
        choices.remove(index);
        
        if guess != random {
            println!("{}",
                format!("You haven't picked {:?}", choices.fg::<CustomColor<255, 110, 110>>()));
        }

        match guess.cmp(&random) {
            Ordering::Less => println!("Too small!"),
            Ordering::Greater => println!("Too big!"),
            Ordering::Equal => { 
                println!("{}", "You win!😎".blue().bold());
                break;
            }
        };
    }
}

关键说明:

  1. Option类型匹配:position方法找到元素时返回Some(index),找不到时返回None,通过match分支分别处理有效/无效输入
  2. 提前跳过无效循环:当返回None时,提示用户重复输入,用continue直接进入下一轮猜测,跳过当前循环的后续逻辑
  3. 类型安全保证:Some分支返回usize类型索引,None分支通过continue提前退出,避免了之前的类型不匹配错误

修改后,重复输入已猜过的数字时,程序会友好提示并继续运行,不会触发panic。

内容的提问来源于stack exchange,提问作者rubysxy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 15:55:18