|
|
Subscribe / Log in / New account

Casts are a known problem

Casts are a known problem

Posted Jul 3, 2025 11:54 UTC (Thu) by farnz (subscriber, #17727)
In reply to: Are casts encouraged in Rust? by alx.manpages
Parent article: How to write Rust in the kernel: part 2

Casts are a known problem, and (AIUI) people are working to make the "as conversions" clippy lint a warn-by-default lint. There's some issues to resolve before we get there:

  • To do a good job, we need a way to say "you can implement a trait with either const fn or fn, and if you use const fn, we can use this in a const context". We can't, however, say that all conversions happen in a const context, partly for backwards compatibility, and partly because we still want to support conversions that can't be done in a const context. But this would let us support let x: u16 = y.into(); type of safe conversion, or const z: u16 = y.try_into().unwrap_or_else(0);.
  • There needs to be a carefully considered plan for handling fallible conversions sensibly, and allowing you to choose behaviours. For example, converting u32::MAX to f32 could be a bug, and a reason for a good compile-time error (because f32 has 24 bits of precision, while u32 has 32), or you could want to round down to the first f32 below u32::MAX, or even round up to the next f32 above u32::MAX.
  • You don't want to make the obviously correct code unclear or hard to write. If a conversion is, in general, fallible, but in this specific instance is known to be infallible, I should be able to use an infallible conversion operator. For example, const MAX_SIZE: usize = 0xfe; const ERROR_INDICATOR: u8 = MAX_SIZE.into(); should work, since it's obviously possible to convert 0xfe to a u8, and you don't want to force people to write const ERROR_INDICATOR: u8 = MAX_SIZE.try_into().expect("Too big for u8"); when it's obviously infallible in context.

There's thus a lot of design work in getting this right; it's OK if the initial solution only solves for some of these problems, as long as it doesn't block off useful bits of the design space for other solutions. I'd thus expect that we'll have a decent solution to the first problem - traits usable in const and non-const contexts if they implement a function as const fn, but only in non-const contexts if they implement it as fn - long before the other 2 get solved, because it's the lynchpin on which the other two stand - and indeed, work on this is actively happening, leading to an early design that's being pushed around until people are confident that it's a good design.


to post comments


Copyright © 2025, Eklektix, Inc.
Comments and public postings are copyrighted by their creators.
Linux is a registered trademark of Linus Torvalds