如果数组索引超出范围,如何继续?



假设我有这个数组-[1, 2, 3, 4, 5]-并且我试图访问一个不存在的索引(假设6)。它通常会通过一个错误。但有没有一种方法可以让我完全忽略这个错误,像什么都没发生一样继续呢?

数组([T; N]具有固定大小,N在编译时已知)可以自由地强制转换为片([T]具有运行时已知的可变长度),因此当您有一个数组时,您可以访问slice方法的广泛数组。

对于您的用例,slice::get返回Option<T>。如果索引是有效的,你得到Some(value),如果索引是无效的,你得到None

的例子:

let array = [1, 2, 3, 4, 5];
let index = 6;
if let Some(value) = array.get(index) {
println!("Found {} at array[{}]", value, index);
}
else {
println!("array[{}] is out of bounds", index);
} 
输出:

array[6] is out of bounds

<一口>操场

如果数组索引为负,则会得到编译时错误,因为它必须为usize类型。

如果为正数,则可以将其与数组的长度进行比较。

要处理超出边界的索引(在本例中为6),您可以这样做:

fn get_item(input_array: &[i8; 5], index: usize) -> i8 {
if index >= input_array.len() {
-1
} else {    // continue
input_array[index]
}
}
#[test]
fn test_get_item() {
assert_eq!(get_item(&[1, 2, 3, 4, 5], 2), 3, "Value at index 2 is 3");
}
#[test]
fn test_get_item_out_of_bounds() {
assert_eq!(
get_item(&[1, 2, 3, 4, 5], 6),
-1,
"Array index out of bounds"
);
}

最新更新