|
|
Log in / Subscribe / Register

Are casts encouraged in Rust?

Are casts encouraged in Rust?

Posted Jul 1, 2025 1:00 UTC (Tue) by iabervon (subscriber, #722)
In reply to: Are casts encouraged in Rust? by alx.manpages
Parent article: How to write Rust in the kernel: part 2

I'd actually say that the C compilers are suboptimal here because they don't give a warning about line 13: if you want to get 0 directly, you should just use 0, and, in the more likely event that 65336 is coming from a macro or other constant and you want to just get the low bits into this constant (with the high bits going elsewhere), you should probably write it as VALUE & 0xffff, and I don't see any reason that writing (uint16_t) VALUE shouldn't give you a warning about the explicit cast resulting in a different constant value.


to post comments

Are casts encouraged in Rust?

Posted Jul 1, 2025 2:14 UTC (Tue) by alx.manpages (subscriber, #145117) [Link]

> I'd actually say that the C compilers are suboptimal here because they don't give a warning about line 13

Line 13 has a cast, which precisely means: "compiler, please shut up".

If you want a diagnostic, remove the cast. As I've said, the appropriate number of casts in almost any given program is 0.


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