Str.to_char() for full strings

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.

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

.first()?

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

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

1 Like

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

you would need to handle the error type, but

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

would work

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.