Hi, all. I'm considering a kind of unsafe
construct that is lexically limited. I'm not sure whether this is suitable as a Pre-RFC or RFC. Any feedback is appreciated.
Consider the following code:
if unsafe { foo.check_condition() } {
unsafe { foo.work() }
}
This is unpleasant due to repeated unsafe
s. One may want to rewrite it as:
unsafe {
if foo.check_condition() {
foo.work()
}
}
This introduces another level of indentation.
unsafe { if foo.check_condition() {
foo.work()
}}
Better, but the braces of unsafe
still look redundant and ugly.
I think it would be nice if one is able to write:
unsafe if foo.check_condition() {
foo.work()
}
The semantics are: both the condition expression and the body are marked unsafe
, as if it was written
if unsafe { expr } { unsafe { body } }
Additionally, this intuition can apply to other constructs, including while
and loop
.
There are two ways to implement this:
- Extend the grammar to handle
unsafe if
,unsafe while
,unsafe loop
, etc. - Allow
unsafe expr
.
The first one looks easy to implement, as it involves only grammar changes. (I'm not familiar with rustc, so correct me if I'm wrong!) It's also forward-compatible with the second approach if we were to adopt that. However, I will not fight for the second approach here: it needs detailed design.
I'm not sure if this was already proposed before. (There is a related but different proposal on Rust Internals.) IMHO, this is a nice and small improvement of the syntax, and I'd like to see it eventually become part of Rust. If this is OK to be an RFC or a Pre-RFC, I will prepare one.