Search code examples
rustreverseborrow-checker

how to reverse a list without moving in rust


I'm trying to write a simple function to detect palindromes. I couldn't find a way to avoid moving nums while reversing it, so I ended up with the following:

fn is_palindrome(num: String) -> bool {
    let nums: Vec<char> = num.chars().collect();  
    let reversed: Vec<char> = nums.clone().into_iter().rev().collect();  
    nums == reversed         
}

Is there a way to do this without having to use .clone()? Thanks.


Solution

  • As mentioned in the comments, you don't need to collect either the forward or reverse iteration into a vec. In fact you don't even need to consume the input string.

    Instead you can just create a forward iterator, and a reverse iterator, and compare them using the Iterator::eq method:

    fn is_palindrome(num: &str) -> bool {
        num.chars().eq(num.chars().rev())
    }