fn shuffle(nums: Vec<i32>, n: i32) -> Vec<i32> {
let mut res: Vec<i32>;
let mut i = 0;
while i < n {
res.push(nums[i]);
res.push(nums[n + i]);
i += 1;
}
res
}
当我尝试索引 nums
数组以获取 [i]
处的值时,出现此错误:
the type [i32] cannot be indexed by i32
the trait SliceIndex<[i32]> is not implemented for i32
required because of the requirements on the impl of Index<i32> for Vec<i32>
任何想法如何解决这个问题?
答案 0 :(得分:0)
您只能使用 Vec
索引 usize
,因此您必须将 i32
转换为 usize
才能索引到 nums
:
fn shuffle(nums: Vec<i32>, n: i32) -> Vec<i32> {
let mut res = Vec::new();
let mut i = 0;
while i < n {
res.push(nums[i as usize]);
res.push(nums[(n + i) as usize]);
i += 1;
}
res
}