0
  str.split_whitespace()
        .map(|w| w[..1].to_uppercase() +&w[1..].to_lowercase())
        .collect()

w[0] and w[..1] are exactly the same, but I know that using w[0] caused an error. I want to know why the error occurred.

What i know about both of them: w[0] returns a single character, and w[..1] returns a string slice containing the first character.

cafce25
  • 15,907
  • 4
  • 25
  • 31

1 Answers1

1

"w[0] returns a single character", no, &str isn't indexable by usize (or any integer) because indexing always produces references to internals of self and you yourself expressed you'd expect a char but there just aren't any chars we could reference to begin with since strings are stored UTF-8 encoded in a string slice.

To avoid errors Rust doesn't provide a Index<usize> for &str at all but you can still explicitly tell Rust which interpretation (u8 or char) you want using either of the as_bytes, bytes or chars methods to get a byte slice, iterator over u8, iterator over char respectively. You can 'index' the iterators using nth

cafce25
  • 15,907
  • 4
  • 25
  • 31