3 ms·
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 :
by coder543 6y ago
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.
- creata 6y agoAh, 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.
- richardwhiuk 6y agoIt'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_possible_truncation https://rust-lang.github.io/rust-clippy/master/#cast_possibl...
- cesarb 6y agoAnnoyingly, .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).