Home > Software design >  binary assignment operation ` =` cannot be applied to type `&str`
binary assignment operation ` =` cannot be applied to type `&str`

Time:10-02

pub fn is_palindrome(x: i32) -> bool {
    let mut rev = "";

    for n in x.to_string().chars().rev() {
        rev  = n
    }

    return false
}

I'm used to writing this syntax in languages like kotlin, but how should I do this in rust?

CodePudding user response:

"" is an empty string-slice, i.e. a reference to the storage where a sequence of utf-8 characters is placed (actually, it's a sequence of bytes conforming to utf-8 encoding, but that is not exactly the main concern in this question). In general, with a string-slice, nothing says how those characters were stored, thus we cannot change anything to this storage (extend/remove) and moreover a string-slice (&str) is a shared (immutable) reference to this storage preventing from any change. In this peculiar case (a literal as " ... ") the characters are stored in constant memory (consistent with a shared reference) at the process startup.

To extend such a sequence, you need to control how it is stored. In this case, we don't use a string-slice but a String which allocates on the heap the storage for the sequence according to the needs. And, of course, since a String owns its content, it can mutate it (if the String itself is considered mutable).

Appending a char to a String is done with the .push() function.

pub fn is_palindrome(x: i32) -> bool {
    let mut rev = String::new();

    for n in x.to_string().chars().rev() {
        rev.push(n);
    }

    return false;
}

CodePudding user response:

The other answers are of course correct and one of them should be the accepted answer.

I'd just like to point out that the construct for n in iter { y.append(n) } is used so many times that it got implemented in a method of Iterator: collect().

pub fn is_palindrome(x: i32) -> bool {
    let rev = x.to_string().chars().rev().collect::<String>();

    return false;
}

Another remark: to compute whether the forward and reverse of a string are identical, you don't actually need to create the reversed string. You can directly compare its iterators:

pub fn is_palindrome(x: i32) -> bool {
    let x_str = x.to_string();
    x_str.chars().eq(x_str.chars().rev())
}

CodePudding user response:

AddAssign<&str> is implemented for String. Thus you can use = on String.

A simple example:

pub fn is_palindrome(x: i32) -> bool {
    let mut rev = String::new();
    
    for n in x.to_string().chars().rev() {
        rev  = &n.to_string();
    }
    
    return false
}
  • Related