How to Index a String in Rust

Created
Modified

Using as_bytes Function

If the enum is C-like, then you can create a static array of each of the variants and return an iterator of references to them:

fn main() {
  let s = "abc";
  let b: u8 = s.as_bytes()[1];
  let c: char = b as char;
  println!("{}", c);
}
b

Using chars Iterator

The str.chars() method returns an iterator over the [`char`]s of a string slice.

fn main() {
  let s = "abc";
  let c = s.chars().nth(1).unwrap();
  println!("{}", c);
}
b

Related Tags