Are casts encouraged in Rust?
Are casts encouraged in Rust?
Posted Jun 30, 2025 19:53 UTC (Mon) by alx.manpages (subscriber, #145117)In reply to: Are casts encouraged in Rust? by iabervon
Parent article: How to write Rust in the kernel: part 2
In C both compile-time (constexpr) and run-time get a diagnostic, but they're different categories of diagnostics, so you can decide which to turn on and/or off.
alx@debian:~/tmp$ cat c.c | grep -nT ^
1: #include <stdint.h>
2: #include <stdlib.h>
3:
4: constexpr uint16_t X = 65536;
5: constexpr uint16_t Y = (uint16_t) 65536;
6:
7: int
8: main(void)
9: {
10: uint32_t zz = rand(); // generate a run-time u32 for line 14
11:
12: const uint16_t x = 65536;
13: const uint16_t y = (uint16_t) 65536;
14: const uint16_t z = zz;
15: }
alx@debian:~/tmp$ clang -Weverything -Wno-unused -Wno-pre-c23-compat -Wno-c++98-compat -std=c23 c.c
c.c:4:25: error: constexpr initializer evaluates to 65536 which is not exactly representable in type 'const uint16_t' (aka 'const unsigned short')
4 | constexpr uint16_t X = 65536;
| ^
c.c:4:25: warning: implicit conversion from 'int' to 'uint16_t' (aka 'unsigned short') changes value from 65536 to 0 [-Wconstant-conversion]
4 | constexpr uint16_t X = 65536;
| ~ ^~~~~
c.c:10:17: warning: implicit conversion changes signedness: 'int' to 'uint32_t' (aka 'unsigned int') [-Wsign-conversion]
10 | uint32_t zz = rand(); // generate a run-time u32 for line 14
| ~~ ^~~~~~
c.c:14:22: warning: implicit conversion loses integer precision: 'uint32_t' (aka 'unsigned int') to 'uint16_t' (aka 'unsigned short') [-Wimplicit-int-conversion]
14 | const uint16_t z = zz;
| ~ ^~
c.c:12:22: warning: implicit conversion from 'int' to 'uint16_t' (aka 'unsigned short') changes value from 65536 to 0 [-Wconstant-conversion]
12 | const uint16_t x = 65536;
| ~ ^~~~~
4 warnings and 1 error generated.
I think this is more sensible than the Rust approach.
