|
|
Log in / Subscribe / Register

Are casts encouraged in Rust?

Are casts encouraged in Rust?

Posted Jun 30, 2025 2:45 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

Rust uses the word "safe" in a highly specific way. If an operation cannot cause UB, either alone or in conjunction with other safe operations, then it is considered safe. The word "safe" does not mean correct, valid, reasonable, or a good idea.

The reason for this framing is so that unsafe operations can be protected by the unsafe keyword. Determining whether an operation is "correct" is clearly beyond the capabilities of a compiler to prove in full generality, so "no UB" is considered an acceptable substitute. When correctness is desired, the usual approach is to make incorrect states impossible to represent, by constructing a type in such a way that all of its valid instances represent valid states or operations. Since producing an invalid instance of a type (e.g. an enum instance which is not any of the enum's variants, a bool with a value other than true or false, or any uninitialized value that occupies nonzero space and isn't MaybeUninit<T>) is considered UB in Rust, this has the practical effect of tying correctness to safety for the purpose of that specific type. If you find a way to do something like this over an entire program, then in principle you can use the Curry-Howard isomorphism to convert that type construction into a proof of correctness, which in turn could be used to formally verify the program. But that kind of construction can get very complicated, and may not be worth it in all situations, hence the existence of unsafe as an escape hatch.


to post comments


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