stringrust

How to get the last character of a &str?


In Python, this would be final_char = mystring[-1]. How can I do the same in Rust?

I have tried

mystring[mystring.len() - 1]

but I get the error the type 'str' cannot be indexed by 'usize'


Solution

  • That is how you get the last char (which may not be what you think of as a "character"):

    mystring.chars().last().unwrap();
    

    Use unwrap only if you are sure that there is at least one char in your string.


    Warning: About the general case (do the same thing as mystring[-n] in Python): UTF-8 strings are not to be used through indexing, because indexing is not a O(1) operation (a string in Rust is not an array). Please read this for more information.

    However, if you want to index from the end like in Python, you must do this in Rust:

    mystring.chars().rev().nth(n - 1) // Python: mystring[-n]
    

    and check if there is such a character.

    If you miss the simplicity of Python syntax, you can write your own extension:

    trait StrExt {
        fn from_end(&self, n: usize) -> char;
    }
    
    impl<'a> StrExt for &'a str {
        fn from_end(&self, n: usize) -> char {
            self.chars().rev().nth(n).expect("Index out of range in 'from_end'")
        }
    }
    
    fn main() {
        println!("{}", "foobar".from_end(2)) // prints 'b'
    }