这有什么问题:
fn main() {
let word: &str = "lowks";
assert_eq!(word.chars().rev(), "skwol");
}
Run Code Online (Sandbox Code Playgroud)
我收到这样的错误:
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
Run Code Online (Sandbox Code Playgroud)
这样做的正确方法是什么?
bri*_*tar 42
因为,@DK.建议,在稳定版本中.graphemes()
不可用&str
,你可能只是做了@huon在评论中建议的内容:
fn main() {
let foo = "palimpsest";
println!("{}", foo.chars().rev().collect::<String>());
}
Run Code Online (Sandbox Code Playgroud)
DK.*_*DK. 29
第一个也是最基本的问题是,这不是你如何反转Unicode字符串.您正在颠倒代码点的顺序,您要在其中颠倒字形顺序.可能还有其他问题,我不知道.文字很难.
第二个问题由编译器指出:您正在尝试将字符串文字与char
迭代器进行比较. chars
并且rev
不产生新的字符串,它们产生惰性序列,就像通常的迭代器一样. 以下作品:
/*!
Add the following to your `Cargo.toml`:
```cargo
[dependencies]
unicode-segmentation = "0.1.2"
```
*/
extern crate unicode_segmentation;
use unicode_segmentation::UnicodeSegmentation;
fn main() {
let word: &str = "low?ks";
let drow: String = word
// Split the string into an Iterator of &strs, where each element is an
// extended grapheme cluster.
.graphemes(true)
// Reverse the order of the grapheme iterator.
.rev()
// Collect all the chars into a new owned String.
.collect();
assert_eq!(drow, "skw?ol");
// Print it out to be sure.
println!("drow = `{}`", drow);
}
Run Code Online (Sandbox Code Playgroud)
请注意,graphemes
以前在标准库中作为一种不稳定的方法,因此上面的内容会破坏足够旧版本的Rust.在这种情况下,您需要使用UnicodeSegmentation::graphemes(s, true)
.