Palindrome Check With Rev Chars
Check palindromes by comparing chars() against chars().rev(), exercising DoubleEndedIterator equality without allocating a reversed copy.
Code
fn is_palindrome(text: &str) -> bool {
// 双端迭代器:chars 正向与逆向逐对比较,eq 会同时消费两侧
text.chars().eq(text.chars().rev())
}
fn main() {
for word in ["level", "rust", "racecar", "abcba"] {
println!("{} -> {}", word, is_palindrome(word));
}
// 空串与单字符平凡回文:正逆序天然相等
println!("empty -> {}", is_palindrome(""));
println!("x -> {}", is_palindrome("x"));
// rev 只对 DoubleEndedIterator 可用:切片迭代器同样满足
let digits = [1, 2, 3, 2, 1];
println!("array palindrome: {}", digits.iter().eq(digits.iter().rev()));
}How it works
Palindrome Check With Rev Chars comes down to the functions is_palindrome and main.
for word in ["level", "rust", "racecar", "abcba"] is the loop that carries the per-item work.
What to watch for
- The toolchain alone is enough — no dependency resolution happens.
Using it
Signature: fn is_palindrome(text: &str) -> bool
The run emits 3 labeled sections — empty ->, x ->, array palindrome: — one per step.
There are 1 call inside main — is_palindrome — executed top to bottom.
Key statements
fn is_palindrome(text: &str) -> bool {
// 双端迭代器:chars 正向与逆向逐对比较,eq 会同时消费两侧
text.chars().eq(text.chars().rev())
}
Interactive Tools for This Topic
FAQ
- What does Palindrome Check With Rev Chars print when run?
- Execute the whole file; each printed line is prefixed with a label like `empty ->`, `x ->`, `array palindrome:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.