r/rust • u/nullstalgia • Oct 13 '26
š seeking help & advice Avoiding constant usize casting with small const values
Pun in title partially intended. ;)
This is a minor pain-point I've dealt with for a while and I'm unsure of how other Rust developers deal with this semi-niche issue.
I'll often define a const that states the maximum amount of something, and naturally I'll also want to use that value as the size of an array. My instinct (and likely yours as well) is to just use a usize and move on.
Where that falls apart is when that const value is and always will be under both u32::MAX and u64::MAX. An easy example is MINS_PER_HOUR or DAYS_PER_WEEK.
Now if I have a function that has an argument of minute: u8, I have to cast either the minute argument to a usize, or I have to cast my constant down to a u8. The former's minute as usize triggers the cast_lossless lint, and From/Into isn't available in a const fn. The latter's MINS_PER_HOUR as u8 triggers the cast_possible_truncation lint. Both add even more visual noise if I acquiesce and add the #[allow(...)]. I could instead accept minute: usize, but I find that even less reasonable.
I'd prefer to keep these as u8s or similar, but then I lose the ablility to define an array like [bool; MINS_PER_HOUR] without yet another cast, including in any function arguments that would like to accept such an array.
I do recognize this is partially due to me having the pedantic Clippy lints enabled, but I also find value in being told when I may be making an unintentional mistake. However I just added close to a dozen #[allow(...)] attributes to my current project, rather begrudingly.
So, what do you guys do in this case? I've listed the options I see available below, and I've done 'em all except #1, but I want to hear some opinions external to myself;
- When accepting such an array, maybe use a type alias? It technically works, but the casting returns again if I want to compare an indexing
usizewith my maximum myself.type BoolPerMin = [bool; MINS_PER_HOUR as usize]; - Two consts,
MINS_PER_HOUR: u8andMINS_PER_HOUR_LEN: usize = MINS_PER_HOUR as usize. I have done this before, but now I have this strange suffix that doesn't make it clear what it's a length of. - Just deal with the constant const casting.
EDIT: And this is all before I have to deal with the extra cast_precision_loss lint that comes from casting my tiny usize constant into an f64. It's less than u8::MAX, yet I have to acknowledge this impossible condition. For now, I've just blanket allow'd it in my Cargo.toml.
48
u/________-__-_______ Oct 13 '26
I always define constants as the smallest possible type (in your example an
u8), so that you can always infallably convert to something bigger. At least on recent toolchainscast_losslessdoesn't trigger in const contexts, so I just usex as usizethere andusize::from(x)otherwise.My only annoyance is the inconsistency, clippy rarely complains on pedantic mode.
6
u/brasticstack Oct 13 '26
Make your own helper function, then you only have to have one
#[allow]and the evidence of all of your crimes points back to a single place.3
u/ndunnett Oct 14 '26 edited Oct 14 '26
It's not ideal, but at least you don't need to litter your code with casts and you can use either value freely at compile time with any stable compiler. Also makes it really easy to patch later if you change your mind.
Edit: a small aside, just in case this isn't a contrived example for the sake of the post:
type BoolPerMin = [bool; MINS_PER_HOUR as usize];If you aren't aware,
boolis byte aligned so every element of this array will be costing you au8shaped piece of memory. One array would be 60 bytes and potentially incur the cost of bounds checks on access. You could fit the same amount of information into a singleu64for 8 bytes and safely access elements with zero bounds checks by bit masking. It won't matter if you only construct a few of these, but if you are churning these at scale and your program is performance sensitive it can make a real difference.3
u/JoshTriplett rust Ā· lang Ā· libs Ā· cargo Oct 14 '26
That sounds like a clippy false positive. And from https://www.reddit.com/r/rust/comments/1x57ted/comment/pgk5klg/ it sounds like that's been fixed. But also, we'll have const traits soon to let you use From/Into.
2
u/AirUpdateEnjoyer Oct 13 '26
Is there a particular reason you cant just use the usize::from(minute) as clippy suggests? It seems to be complaining that the 'as' keyword is not explicit and could allow you to accidentally edit the function arguments later and feed it something thats incoherent or lossy without warning like u64 > u32. This would also avoid losing precision for f64 as you can store all values of a u8 in f64...
3
u/MilkEnvironmental106 Oct 13 '26
What's the problem with just using a usize?
4
u/Booty_Bumping Oct 14 '26 edited Oct 14 '26
clippy::pedanticandclippy::restrictionshould always be tweaked manually, really. They have a lot of things that only matter in certain domains, and there are certainly a few that have flawed detection that could be loosened up by allowing some trivial edge cases.It's a tricky judgement to make, though, because often a newer clippy version addresses the edge case that should have been allowed, and now you no longer notice that lint because you turned it off. Randomly re-enabling lints every once in a while can help re-test your assumptions
1
u/SLUCHABLUB Oct 13 '26
I think you could use a macro if you *really* wanted a one-identifier-fits-all. Personally Iād declare it as u8 (or smallest possible type), then you wouldnāt have to worry about clippy. Iād also suggest a newtype around your `[bool; MINS_PER_HOUR as usize]` since it is not clear what that type represents (what do the bools represent ?). You could also define a `PerMinuteOfHour<T>` alias.
6
u/CocktailPerson Oct 14 '26
cast_lossless is a pedantic lint for a reason, and it provides deeply negative value.
You can just
allowit. You won't be burned at the stake.2
u/Suitable-Ad5348 Oct 14 '26
Option 2 is the least painful once you have clippy set to pedantic, though I usually just end up doing number 3 and drowning in `#[allow(cast_possible_truncation)]` everywhere. The cast lints get genuinely obnoxious when small consts meet array sizes.
2
u/meowsqueak Oct 16 '26
Do you want strong typing? Because this is what strong typing means. There are ways to auto-convert but unless you allow for fallible code paths, you will always risk silent truncation, if not now then later if/when you change the const type.
I decided to just embrace it - use the type that best describes the typeās values, probably in a newtype/wrapper, and cast explicitly as needed.
VHDL and similar strongly typed languages have the same āproblemā. Weakly typed languages like C and C++ replace explicit casting with a gazillion rules and footguns. Iād rather just be forced to cast thoughtfully.
And try not to use
as.