I want a chunks
function that takes an array and returns an array of slices of the array.
-
First parameter is (a ref for) the array.
-
Second parameter is the length of the first chunk.
-
Third parameter is the length of subsequent chunks.
-
A
0
{second, third} parameter means “just pass a slice of the rest”.
Say l = [1,2,3,4,5]
, then:
chunks(l, 0, 0) -> [ [1,2,3,4,5] ]
chunks(l, 1, 0) -> [ [1], [2,3,4,5] ]
chunks(l, 1, 1) -> [ [1], [2], [3], [4], [5] ]
chunks(l, 1, 3) -> [ [1], [2,3,4], [5] ]
chunks(l, 2, 0) -> [ [1,2], [3,4,5] ]
chunks(l, 2, 1) -> [ [1,2], [3], [4], [5] ]
chunks(l, 2, 2) -> [ [1,2], [3,4], [5] ]
etc...
So, I try:
fn chunks(list: &[i32], first_chunk: i32, later_chunks: i32) -> [&[i32]] {
[list] // stub implementation, to be implemented after compiler is happy
}
But rustc complains about the output type:
the size for values of type
[&[i32]]
cannot be known at compilation time
Which makes sense. So let’s return a reference, right?
fn chunks_2(list: &[i32], first_chunk: i32, later_chunks: i32) -> &[&[i32]] {
&[list] // stub implementation, to be implemented after compiler is happy
}
But compilation now fails with:
cannot return reference to temporary value
returns a reference to data owned by the current function…further detailed by
rustc --explain E0515
, which says:Consider returning an owned value instead
Uh but yes, I do want to return a reference, because I don’t know the size of the output, because of step 1! And surely enough, if I come back to returning a value, then I get back my initial error that the size for values of type [&[i32]] cannot be known at compilation time
. What should I do?
- Is this a case where I should take a mutable reference where my function would write, à la C?
- Should I look into iterators? (I want to, but first I wanted to try a simpler approach with just a function).
- Something entirely else?
I’m running rust 1.31.1. Thanks for the help .