gpt4 book ai didi

rust - 线程 'main' 在 'index out of bounds: the len is 2 but the index is 2' 崩溃时 panic

转载 作者:行者123 更新时间:2023-11-29 08:26:10 24 4
gpt4 key购买 nike

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.

我怎样才能让我的程序正常退出而不会崩溃?

最佳答案

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

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

关于rust - 线程 'main' 在 'index out of bounds: the len is 2 but the index is 2' 崩溃时 panic ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57749069/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com