Sometimes, a construct like the following one is used.
let a = {
let b = ...;
// ...
};
I think it would look prettier with if let (it's also idiomatic in many lisps)
let a = if let b = ... {
// ...
};
But rust can likely fail with either https://doc.rust-lang.org/error-index.html#E0317 or https://doc.rust-lang.org/error-index.html#E0162 if in the place of ... we have a known value
I'm not sure I understand. if let and let have completely different semantics.
Do you mean to yield two values?
let (a, b) = {
// ...
(a_value, b_value)
};
@oli-obk
I guess what @fwrs means is that, as let b = ... is a irrefutable pattern matching, no else branch would be reachable or needed. Thus the proposed semantics is legit, and would be prettier and more idiomatic comparing to the current construct.
A concrete example:
Current
let a = {
let b = 1;
b + 1
};
Proposed
let a = if let b = 1 {
b + 1
};
I'm not sure the above incentive is strong enough though.
I don't understand why you'd want an if there. There's no conditional code execution going on
I think I'd expect it to be something more SML-like, maybe
let foo_squared =
let x = foo()
in x * x;
(Though I'm not convinced that's worth supporting when the block works fine.)
You can write it like this if you want to :man_shrugging::
let a = { let b = 1;
b + 1
};
There's also this, which is closer in semantics to let ... in (in terms of temporary scopes):
let a = match 1 {
b => b + 1
};
I'd suggest using a new keyword "with" for a construct like this. It already has similar usage as a keyword to specify RAII-style object disposal in other languages, and it suggests the right idea to someone not familiar with it.
Something like:
let a = with b = 1 {
b + 1
}
Introducing language concepts for seldom useful stuff like this would only confuse people. You don't even save any time from typing it out and it removes no boilerplate.
Fair enough. At the same time, I don't want to be put in the position where I'm cracking my head over rust code for hours, just to realize that "if" is syntactically overloaded to also "plant" variable within scopes.
See c++ operator overloading and why some people will argue for days on end why it's a bad thing even though it makes many expressions cleaner.
@eaglgenes101 But it's not, the let in if let and while let is what's declaring the variables.
This seems resolved per https://github.com/rust-lang/rfcs/pull/2086.
Most helpful comment
I don't understand why you'd want an
ifthere. There's no conditional code execution going on