I have the following code-snippets (don't question the sense of them ;) )
1. get the n-th element of a Vec recursively
fn helper<T: Clone>(n: usize, current_n: usize, current_xs: &Vec<T>, accumulator: Option<T>) -> Option<T> {
if current_n > n {
accumulator
} else {
let head = current_xs.get(0).cloned();
let tail = current_xs.clone().into_iter().skip(1).collect();
return helper(n, current_n + 1, &tail, head);
}
}
2. get the length of a Vec recursively
fn helper<T: Clone>(current_xs: &Vec<T>, accumulator: usize) -> usize {
if current_xs.is_empty() {
accumulator
} else {
let tail = current_xs.clone().into_iter().skip(1).collect();
return helper(tail, accumulator + 1)
}
}
My Question is about that line:
let tail = current_xs.clone().into_iter().skip(1).collect();
In the first example the tail
variable is of Type Vec<T>
and in the second example the tail
variable is of type &Vec<?>
.
Questions:
- Why? Why returns the the exact line of code two different types?
- How can I return a
Vec<T>
in the second example?