New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Unable to Utilize unsafe {}
Blocks as an Expression
#98093
Comments
Works on playground. Could you share the full MCVE? |
Here is the error I am currently running into in my codebase: Not sure if it is my problem or not. |
The issue seems to occur in the playground as well if the statement is by itself on a line as in the original example. |
That issue has nothing to do with |
As stated in The Rust Reference, under Expression statements (emphasis added):
Accordingly, the block is parsed as a statement and must have unit type—but it does not (giving rise to the first error). The I therefore think this is by design and not an issue. @rustbot label +invalid |
Error: Label invalid can only be set by Rust team members Please let |
Consider that let foo = unsafe { /* some stuff here */ };
foo == /* something */ is allowed, is it wrong to consider that the Additionally, I am quite sure that it is common for programmers to flatten the condition, writing something like unsafe { /* some stuff here */ } == /* something */ for the return value of a function, etc. Is my interpretation incorrect or am I misunderstanding something? If so I am more than happy to be corrected in this scenario. |
The block can be an expression, but in some contexts it's ambiguous whether it's an expression or a statement and in those cases Rust opts for it to be a statement. Basically, Rust parses the code as if you had written a If the rule in such ambiguous situations was changed so that blocks were expressions rather than statements, then a lot existing Rust code would no longer compile. Consider for example: unsafe {
foo()
}
bar(); Even worse, this same ambiguity would also then be resolved differently for control flow blocks such as if test {
foo()
}
bar();
|
I've opened https://internals.rust-lang.org/t/expression-vs-statement-ambiguities/16823 to discuss this, potentially with a view to a language RFC if the idea is well received. |
Marking this as a diagnostics issue. From the perspective of the Rust grammar, there's nothing wrong here but ideally the parser would provide actionable hints. |
I tried this code:
I expected to see this happen: compilation succeeds.
Instead, this happened: two errors are emitted.
Meta
rustc --version --verbose
:Even though I know that I can simply wrap the entire
unsafe
block with parentheses, but this still doesn't seem right when anif
block can be combined with boolean expressions in a similar fashion:I know that the
if
case seem to be very spaghetti, but I feel likeunsafe
blocks should exhibit this same behaviour during compilation.The text was updated successfully, but these errors were encountered: