I am trying to return the values of a vector:
fn merge<\'a>(left: &\'a [i32], right: &\'a [i32]) ->
The compiler is telling you that it is impossible to return a [T]
.
Rust has owned vectors (Vec
), slices (&[T]
) and fixed-size arrays ([T; N]
, where N
is a non-negative integer like 6
).
A slice is composed of a pointer to data and a length. This is what your left
and right
values are. However, what isn't specified in a slice is who ultimately owns the data. Slices just borrow data from something else. You can treat the &
as a signal that the data is borrowed.
A Vec
is one thing that owns data and can let other things borrow it via a slice. For your problem, you need to allocate some memory to store the values, and Vec
does that for you. You can then return the entire Vec
, transferring ownership to the caller.
The specific error message means that the compiler doesn't know how much space to allocate for the type [i32]
, because it's never meant to be allocated directly. You'll see this error for other things in Rust, usually when you try to dereference a trait object, but that's distinctly different from the case here.
Here's the most likely fix you want:
fn merge(left: &[i32], right: &[i32]) -> Vec {
let mut merged = Vec::new();
// push elements to merged
merged
}
Additionally, you don't need to specify lifetimes here, and I removed the redundant type annotation on your merged
declaration.
See also: