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");
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
charrepresents 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 StringHlet 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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With