|
|
Log in / Subscribe / Register

Are casts encouraged in Rust?

Are casts encouraged in Rust?

Posted Jun 29, 2025 20:44 UTC (Sun) by excors (subscriber, #95769)
In reply to: Are casts encouraged in Rust? by alx.manpages
Parent article: How to write Rust in the kernel: part 2

Casts are still bad. But I think the reason it doesn't need casts in C is that phy_read() returns an int which contains either an unsigned 16-bit value or an error that's usually represented as a negative error code (but sometimes as 0xffff). Once the caller has checked for negative error codes, the value is semantically a u16 but still stored in an int (because C makes it hard to use the correct type here), and gets bit-masked with constants that are semantically u16 but actually an int literal (via the uapi #define, which doesn't specify a type so C defaults to int). That doesn't seem ideal either.

The Rust driver's dev.read() returns a semantically-appropriate Result<u16>, which becomes u16 after handling the error case. The uapi module is mechanically generated from the C code, and I think it emits the constants as (probably?) i32 because it doesn't know how the constants are going to be used so it'll pick a default. So you need a cast from i32 to u16, which is ugly. The nice solution would be to get uapi to define the constants as u16, but those definitions need to be shared between C and Rust, and the C code doesn't use the correct types.


to post comments


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