How to reverse a Rust String inplace using recursion?

When reversing a String using recursion, I found it difficult to proceed parts of the String to the next because a slice is the &str type not a String.

This doesn't run:

fn reverse_string(s: &mut String) {
    if s.is_empty() {
        return;
    }
    // how to pass a correct parameter?
    reverse_string(&mut s[1..]);
    s.push(s.chars().nth(0).unwrap());
    s.remove(0);
}
error[E0308]: mismatched types
 --> src/lib.rs:6:20
  |
6 |     reverse_string(&mut s[1..]);
  |                    ^^^^^^^^^^^ expected struct `String`, found `str`
  |
  = note: expected mutable reference `&mut String`
             found mutable reference `&mut str`


Read more here: https://stackoverflow.com/questions/65702283/how-to-reverse-a-rust-string-inplace-using-recursion

Content Attribution

This content was originally published by XM Zg at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: