Are casts encouraged in Rust?
Are casts encouraged in Rust?
Posted Jun 30, 2025 20:51 UTC (Mon) by NYKevin (subscriber, #129325)In reply to: Are casts encouraged in Rust? by alx.manpages
Parent article: How to write Rust in the kernel: part 2
I disagree.
1. The first error ("constexpr initializer evaluates to 65536...") is also a hard error in Rust by default (see https://doc.rust-lang.org/rustc/lints/listing/deny-by-def...). You can turn it into a warning if you really want to, but I've never heard of anyone choosing to do that.
2. Any warning that mentions an "implicit conversion" in C is a hard error in Rust, and can't be turned into a warning, because Rust simply does not implement those implicit conversions in the first place. You have to write explicit casts or into()/try_into().
Since I can't imagine you are disagreeing with Rust's handling of (1), that leaves us with (2). But I have to say, I have never encountered a situation where C's implicit conversions were anything other than a headache to deal with. I do not want the language magicking my data into a different type without telling me, especially in contexts where I never even asked for a conversion, such as the following:
uint16_t x = 1; // 1 converted from int to uint16_t
uint16_t y = x + 1; // Both operands converted to int, added, then converted back to uint16_t.
// Sure, *this* case is trivial and safe, but is that true every time you write something like this?
In Rust, the literal 1 is ambiguous, but would be interpreted as 1u16 in context (i.e. "a u16 with the value 1"), which is exactly what a reasonable person would expect it to mean.
