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"); 
1
  • 1
    If you happen to be already using itertools: letter.chars().exactly_one().expect("not exactly one") Commented Jan 7, 2022 at 5:56

1 Answer 1

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:

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.