Str.to_char() for full strings


#1

Specifically, for a &str of 1 unicode scalar value, there should be a .to_char() available to turn it into a char. This is useful when taking e.g. a hexadecimal digit from a DB and calling .to_digit(16) on it. If the string contains more than 1 unicode scalar value, this method should panic (on debug builds. may not panic on release builds. fallback to using only the first char/scalar value when not panicking).

Sometimes, especially when dealing with legacy data, it makes sense to get rid of unicode. Rust makes getting rid of unicode extremely painful and everything you try will bite you - even CStrings aren’t well supported and you can’t use them as an alternative to Strings. Small tweaks such as str.to_char() or even str.to_digit(radix) would make this transition much more painless.


#2

Isn’t this the same as string.chars().first().unwrap()?


#3

.first()?


#4

because char implements ‘FromStr’, you can use str::parse() for this.

https://play.rust-lang.org/?gist=36f58820a64525680f1e9123db21365e&version=stable


#5

can I use that as in s.parse().to_digit(16)?


#6

you would need to handle the error type, but

s.parse::<char>().unwrap().to_digit(16)

would work