问题
I need to convert a one element &str
into char
. I was able to come up with this solution that also works for String
:
fn main() {
let comma: &str = ",";
let my_char = comma.chars().nth(0).unwrap();
assert_eq!(my_char, ',');
}
Is there a better or shorter way to do it?
回答1:
No huge improvements I can think of, but a few notes:
- You could replace
.nth(0)
with.next()
, which does basically the same thing. - You should ideally not use
.unwrap()
, since if the string is empty, your program will panic. - If you really must panic, ideally use
.expect("msg")
, which will give users a better idea of why you panicked.
Taking those together:
fn main() {
let comma: &str = ",";
let my_char = comma.chars().next().expect("string is empty");
assert_eq!(my_char, ',');
}
The only other thing to note is that "one element" is a somewhat dangerous thing to talk about. For example, "é"
has one char
, but "é"
has two (the first is a pre-composed U+00E9, whilst the second is a regular e
followed by a U+0301 combining ◌́).
来源:https://stackoverflow.com/questions/33405672/how-can-i-convert-a-one-element-string-into-a-char