正常语言的数组切片:
a = [1,2,3]
print(a)
但是实际上讲,如果a为空时,在Python中,其返回为空。
Rust中也可以使用,但是!先决条件是你的数组得到了初始化:
let mut a[i32;3] = [1,2,3];
println!("{:?}",a[0]);
倘若你的数组动态数组没有初始化呢?
error [E0381]: used binding `a` isn't initialize
叮咚!喜提报错+1,Rust认为:你的数组连元素都没有你取个毛线?因此Rust并不会惯着你,像其它编程语言一样返回空值。
那么我如果使用的是进行std::Vec
进行初始化的呢?你可以取出数组,就像这样:
fn main() {
let mut a:Vec<i32> = Vec::new();
a.push(1);
println!("{:?}",a[0]);
}
但是如果我是函数需要调用一个参数进行循环取值,例如n阶斐波那契数列呢?
fn fibo(n:i32) -> Vec<i32>{
let mut arr:Vec<i32> = Vec::new();
for i in 1..n+1{
if i == 1 || i == 2{
arr.push(1);
} else {
/*
如果直接使用 arr[i] = arr[i-2] + arr[i-3] 会报错
因为对Vec或数组进行切片时,需要使用usize类型的索引
因此,需要使用 进行类型转换
*/
arr.push(arr[i - 2] + arr[i - 3]);
}
}
return arr
}
叮咚!又喜提报错+1:
error[E0277]: the type `[i32]` cannot be indexed by `i32`
我发动我这颗由单核奔腾构建的大脑飞速运转,也没想明白这是为什么,而官方的想法则是让我把i32
类型的i
转换为usize
类型的i
后再索引。
= help: the trait `SliceIndex<[i32]>` is not implemented for `i32`
= help: the trait `SliceIndex<[T]>` is implemented for `usize`
= note: required for `Vec<i32>` to implement `Index<i32>`
所以最简单的方法是:将fibo
的参数从n:i32
改写为n:usize
。
另外Rust不支持负数切片,取而代之则是使用arr.len() - 从后往前数的索引
。