-
Notifications
You must be signed in to change notification settings - Fork 1.6k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Impl TryFrom<char> for u8 #2854
Comments
This differs from |
@kennytm Good point! Thanks for pointing out the semantic difference in |
if all of 0..=255 is allowed I believe what you want can be done as follows: if c as u32 <= u8::max_value() as u32 {
Some(c as u8)
} else {
None
} |
@Lokathor Thanks for the code sample! That's actually very similar to what I've incorporated into my own project, so it's nice to see external confirmation that this general pattern exists. I was hoping to at least raise some discussion on whether a similar conversion could or should be included as part of the standard library. |
This also works: |
If this is added, I'd prefer if it's a method on |
“Latin-1” may refer to slightly different things though.
Back to Rust API naming, we already have the precedent of |
FWIW, I think this makes sense. In general, any time there's EDIT: Said otherwise, we have |
Oh? Is there a convention to not provide I think wrapper types improve code quality of course, but sometimes people then use I suppose one guideline would be |
Nothing official, as far as I know. It's just a heuristic I use, since if you can't recover the original, then it generally seems to me like it's doing something non-obvious enough that it would be better as a method with a more illustrative name. (Of course, this is also only for Scrolling through std's The ones that are a bit weirder are things like All that said, #2484 includes some text proposing rules more along these lines. |
Previously suggested in rust-lang/rfcs#2854. It makes sense to have this since `char` implements `From<u8>`. Likewise `u32`, `u64`, and `u128` (since rust-lang#79502) implement `From<char>`.
Implement `TryFrom<char>` for `u8` Previously suggested in rust-lang/rfcs#2854. It makes sense to have this since `char` implements `From<u8>`. Likewise `u32`, `u64`, and `u128` (since rust-lang#79502) implement `From<char>`.
Done in rust-lang/rust#84640, which landed in 1.59.0! 🎉 |
I ran into a case using the
csv
crate in combination withstructopt
where I needed to parse a singlechar
from an argument to use as a CSV delimiter. However, it appears that csv::StringBuilder only acceptsu8
delimiters. I was surprised to see that there was no type-safe way to convert betweenchar
tou8
in the standard library. It would be nice ifu8
implementedTryFrom<char>
, where the conversion fails if thechar
value is outside of the U+0000 to U+00FF codepoint range (0-255).An example use would look like this:
The text was updated successfully, but these errors were encountered: