【问题标题】:My code in rust returns: thread 'main' panicked at 'removal index (is 2) should be < len (is 2)'我的 Rust 代码返回:线程 \'main\' 在 \'removal index (is 2) should be < len (is 2)\' 恐慌
【发布时间】:2023-01-21 15:34:28
【问题描述】:

我正在尝试制作一个程序,使用 rand 来显示猜门的成功率(就像在电视节目中一样)。它编译但不运行。

use rand::Rng;


fn main() {
    let mut right_answers = 0;
    for _ in 0..100 {
        let mut not_already_chosen: Vec<usize> = vec![1, 2, 3];
        let mut rng = rand::thread_rng();

        let right_door = rng.gen_range(1..4);

        let mut guest_choose: usize = rng.gen_range(1..4);
        not_already_chosen.remove(guest_choose);

        let presenter_choose = not_already_chosen[rng.gen_range(0..3)];
        not_already_chosen.remove(presenter_choose);

        guest_choose = not_already_chosen[0];

        if guest_choose == right_door {
            right_answers += 1;
        }
    }
    println!("Rate: {}", (right_answers / 100));
}

当我使用 cargo run 时,它返回:

Compiling choose_the_door v0.1.0 (.../choose_the_door)
    Finished dev [unoptimized + debuginfo] target(s) in 0.47s
     Running `target/debug/choose_the_door`
thread 'main' panicked at 'removal index (is 2) should be < len (is 2)', src/main.rs:16:28
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

我试图删除部分代码以查看问题所在。当我删除具有“not_already_chosen.remove(...);”的行时它可以运行,但代码一开始并没有按照我的意愿进行。我做错了什么?

【问题讨论】:

    标签: rust rust-cargo


    【解决方案1】:

    我做错了什么?

    你用错了Vec::remove。看起来您希望它删除您提供的项目,但它会删除您提供的索引处的项目:

    移除并返回向量中位置索引处的元素,将其后的所有元素向左移动。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-29
      • 1970-01-01
      相关资源
      最近更新 更多