What is wrong with this:
fn main() {
let word: &str = "lowks";
assert_eq!(word.chars().rev(), "skwol");
}
I get an error like this:
error[E0369]: binary operation `==` cannot be applied to type `std::iter::Rev<std::str::Chars<'_>>`
--> src/main.rs:4:5
|
4 | assert_eq!(word.chars().rev(), "skwol");
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
= note: an implementation of `std::cmp::PartialEq` might be missing for `std::iter::Rev<std::str::Chars<'_>>`
= note: this error originates in a macro outside of the current crate
What is the correct way to do this?
Since, as @DK. suggested,
.graphemes()
isn't available on&str
in stable, you might as well just do what @huon suggested in the comments:The first, and most fundamental, problem is that this isn't how you reverse a Unicode string. You are reversing the order of the code points, where you want to reverse the order of graphemes. There may be other issues with this that I'm not aware of. Text is hard.
The second issue is pointed out by the compiler: you are trying to compare a string literal to a
char
iterator.chars
andrev
don't produce new strings, they produce lazy sequences, as with iterators in general. The following works:Note that
graphemes
used to be in the standard library as an unstable method, so the above will break with sufficiently old versions of Rust. In that case, you need to useUnicodeSegmentation::graphemes(s, true)
instead.