Pre-RFC: Add explicitly-named numeric conversion APIs

One thing that is missing from both the current and proposed APIs is a way to do ergonomic casts that panic on out of bounds / overflow. Yes, I can litter my code with unwrap() calls, but there is a reason that Vec supports indexing rather than requiring get().unwrap() calls everywhere: the common option should ideally have the most concise syntax. This absence is especially annoying for u64 <--> usize conversions since in many cases realistically my code is never going to run on anything other than a 64-bit machine, yet I still have to spend mental cycles thinking about it.

That is not how .ceil() , .floor() and .truc() work, they are exactly what you are asking for. I have seen the names misused in the way you described (old versions of Excel), but most programing language (including Rust) follow their mathematical definition.

There is no equivalent for f64 to f32, but I don't see any use them. If someone can provide a good use then we can consider add them in the future.

2 Likes

Prior art:

That RFC proposed what this RFC proposes, basically, and was rejected because library team wanted to try to do it with a trait first (TryFrom).

Differences:

  • cast was used instead of to (wrapping_to -> wrapping_cast).
  • The Option-returning operation followed the analogy with arithmetic operations too (checked_add -> checked_cast, not try_into).
  • The RFC also introduced a simple cast operation that panicked on failure, like simple arithmetic operations (add -> cast).
  • Conversions involving floats weren't considered.

(I still think that RFC did everything right :p)

4 Likes