Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Which is not recommended, because it could silently truncate if _ is a smaller type, or later becomes one as the code is edited over time.

Much better to use ::from() or into() for numeric type conversions, which are only implemented for types that are guaranteed to fit the value, unless you know that truncation is perfectly fine behavior in a particular instance... which it rarely actually is.



Annoyingly, .into() is mostly useless for array indexing, since even when you're compiling for a 64-bit machine (and thus x[my_u32.into()] would be perfectly fine) it's only defined for up to u16 (because you might want the same multi-megabyte code to also work in a tiny microcontroller). If you don't want to use x[my_u32 as usize], you are forced to use x[my_u32.try_into().unwrap()], or just use usize everywhere (of course, you could also use traits to create your own .into_usize() and use it everywhere).


It's fine for increasing width - e.g. u8 -> u16.

There's a lint you can enable to detct truncation - https://rust-lang.github.io/rust-clippy/master/#cast_possibl...


Ah, sorry; I forgot that `as` let you cast bigger types to smaller types. Yeah, that does make the tragically verbose `.into()` the safer option, unless you know that the type you're casting into will always be bigger.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: