Learning Rust: Rust way to program palindrome
⚓ Rust 📅 2026-03-18 👤 surdeus 👁️ 7I have C background, so coded the task in C completely different. However I decided to rewrite my C solutions in Rust. So question is - is the code appropriate for Rust?
trait CharLen {
fn char_len(&self) -> usize;
}
impl CharLen for str {
fn char_len(&self) -> usize {
self.chars().count()
}
}
/// makes a string to palindrome
pub fn palindrome(s: &str) -> String {
let char_len = s.char_len();
let len = s.len();
let odd = char_len % 2 != 0;
let mut rev_s = s.chars().rev();
let center_len = if !odd {
0
} else {
rev_s.next().unwrap().len_utf8()
};
let mut res = String::with_capacity(if odd { len * 2 - center_len } else { len << 1 });
for c in s.chars() {
res.push(c)
}
for c in rev_s {
res.push(c)
}
res
}
As a Rust programmer, how would you implemented the code more efficient and in Rust way?
This is the test block:
mod palindrome;
use palindrome::palindrome;
fn main() -> Result<(), Box<dyn std::error::Error>> {
println!("{}", palindrome("¡¢£¤¥¦§¨©ª«¬®¯°±²³´µ¶·"));
println!("{}", palindrome("Ղ"));
println!("{}", palindrome(""));
Ok(())
}
4 posts - 4 participants
🏷️ Rust_feed