How can I convert a one element string into a char? [duplicate]

落花浮王杯 提交于 2020-06-27 15:39:29

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!