Why won't this compile?
fn isPalindrome<T>(v: Vec<T>) -> bool {
return v.reverse() == v;
}
I get
error[E0308]: mismatched types
--> src/main.rs:2:25
|
2 | return v.reverse() == v;
| ^ expected (), found struct `std::vec::Vec`
|
= note: expected type `()`
found type `std::vec::Vec<T>`
Since you only need to look at the front half and back half, you can use the
DoubleEndedIterator
trait (methods.next()
and.next_back()
) to look at pairs of front and back elements this way:(run in playground)
This version is a bit more general, since it supports any iterable that is double ended, for example slice and chars iterators.
It only examines each element once, and it automatically skips the remaining middle element if the iterator was of odd length.
Read up on the documentation for the function you are using:
Or check the function signature:
The return value of the method is the unit type, an empty tuple
()
. You can't compare that against a vector.Stylistically, Rust uses 4 space indents,
snake_case
identifiers for functions and variables, and has an implicit return at the end of blocks. You should adjust to these conventions in a new language.Additionally, you should take a
&[T]
instead of aVec<T>
if you are not adding items to the vector.To solve your problem, we will use iterators to compare the slice. You can get forward and backward iterators of a slide, which requires a very small amount of space compared to reversing the entire array.
Iterator::eq
allows you to do the comparison succinctly.You also need to state that the
T
is comparable against itself, which requiresEq
orPartialEq
.If you wanted to do the less-space efficient version, you have to allocate a new vector yourself:
Note that we are now also required to
Clone
the items in the vector, so we add that trait bound to the method.