4

This issue seems trivial but I can't find an answer. Assuming that letter is a single character string, how could I convert letter to a char?

let mut letter = String::new();

io::stdin()
    .read_line(&mut letter)
    .expect("Failed to read line");
NaeNate
  • 185
  • 9
  • 1
    If you happen to be already using [itertools](https://docs.rs/itertools/latest/itertools/trait.Itertools.html#method.exactly_one): `letter.chars().exactly_one().expect("not exactly one")` – Caesar Jan 07 '22 at 05:56

1 Answers1

5

One solution is to use chars method. This return an iterator over the chars of a string slice.

let letter_as_char: char = letter.chars().next().unwrap();
println!("{:?}", letter_as_char);

But it is important to remember that

char represents a Unicode Scalar Value, and might not match your idea of what a ‘character’ is. Iteration over grapheme clusters may be what you actually want. For example, Consider the String H

let y = "H";

let mut chars = y.chars();

assert_eq!(Some('H'), chars.next());   
assert_eq!(None, chars.next());

Now consider "y̆"

let y = "y̆";

let mut chars = y.chars();

assert_eq!(Some('y'), chars.next()); // not 'y̆'
assert_eq!(Some('\u{0306}'), chars.next());

assert_eq!(None, chars.next());

See also:

Abdul Niyas P M
  • 18,035
  • 2
  • 25
  • 46