Here's how you get the latter char(which might not be what you think of as a “character”):
mystring.chars().last().unwrap();
Use unwraponly if you are sure that your line has at least one char.
Warning . About the general case (do the same as mystring[-n]in python): UTF-8 strings should not be used through indexing, since indexing is not O (1) (a string in Rust is not an array). Please read this for more information.
, , Python, Rust:
mystring.chars().rev().nth(n - 1)
, char.
Python, :
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))
}