【问题标题】:thread 'main' panicked at 'index out of bounds: the len is 2 but the index is 2' crash线程 'main' 在 'index out of bounds: the len is 2 but index is 2' 崩溃时惊慌失措
【发布时间】:2019-09-01 20:00:12
【问题描述】:
use std::env;
use std::process;

fn main(){
    let mut repository_urls: Vec<String> = env::args().collect();
    if repository_urls.len() == 1 {
        eprintln!("You have to enter at least one repository url!");
        process::exit(1);
    } else {
        for i in 0 .. repository_urls.len() - 1 {
            if repository_urls[i + 1] == "--advanced" && repository_urls.len() >= i + 5 {
                repository_urls.remove(i + 4);
                repository_urls.remove(i + 3);
                repository_urls.remove(i + 2);
            } else {

            }
        }
        //Ends the process normally
        process::exit(0);
    }
}

如果你有 --advanced 1 2 3 作为这个参数,它会做所有事情并按预期执行所有逻辑,但是当它完成时它最终会崩溃:

thread 'main' panicked at 'index out of bounds: the len is 2 but the index is 2', /rustc/a53f9df32fbb0b5f4382caaad8f1a46f36ea887c/src/libcore/slice/mod.rs:2695:10
note: Run with `RUST_BACKTRACE=1` environment variable to display a backtrace.

如何让我的程序正常退出而不会崩溃?

【问题讨论】:

    标签: rust


    【解决方案1】:

    您的直接问题是在您调用remove 三次之后,您的循环继续运行。循环范围 (0..repository_urls.len() - 1) 仅在循环的最开始进行评估。但是现在向量长度已经改变,通过repository_urls[i + 1] 访问向量然后失败。您可以通过在 removes 之后添加 break 来解决此问题。

    对于命令行参数解析,通常建议使用 crate。手动执行通常会导致意大利面条式代码和细微的错误。我非常推荐structopt。将它添加到您的应用程序非常容易。

    【讨论】:

      【解决方案2】:

      在惯用 Rust 中来自@lukas-kalbertodt 的建议之上,您通常在现有向量上创建迭代器,然后使用过滤技术将数据收集到新向量。请避免从向量中非常低效地移除。

      【讨论】:

        猜你喜欢
        • 2023-01-21
        • 2021-05-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-10-18
        • 1970-01-01
        • 2017-04-09
        • 1970-01-01
        相关资源
        最近更新 更多