【发布时间】:2022-10-22 01:21:42
【问题描述】:
假设我有这个数组 - [1, 2, 3, 4, 5] - 我尝试访问一个不存在的索引(比如说 6)。它通常会通过一个错误。但是有什么方法可以让我完全忽略该错误并像什么都没发生一样继续?
【问题讨论】:
-
您不想检查索引是否> =数组长度的任何原因?
标签: rust
假设我有这个数组 - [1, 2, 3, 4, 5] - 我尝试访问一个不存在的索引(比如说 6)。它通常会通过一个错误。但是有什么方法可以让我完全忽略该错误并像什么都没发生一样继续?
【问题讨论】:
标签: rust
数组([T; N] 具有固定大小 N 在编译时已知)可以自由地强制转换为切片([T] 具有在运行时已知的可变长度),因此当您拥有一个数组时,您可以访问广泛的数组slice methods。
对于您的用例,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"
);
}
【讨论】: