rfcs
rfcs copied to clipboard
Allow negation of `if let`
The RFC for if let was accepted with the rationale that it lowers the boilerplate and improves ergonomics over the equivalent match statement in certain cases, and I wholeheartedly agree.
However, some cases still remain exceedingly awkward; an example of which is attempting to match the "class" of a record enum variant, e.g. given the following enum:
enum Foo {
Bar(u32),
Baz(u32),
Qux
}
and an instance foo: Foo, with behavior predicated on foo not being Bar and a goal of minimizing nesting/brace creep (e.g. for purposes of an early return), the only choice is to type out something like this:
// If we are not explicitly using Bar, just return now
if let Foo::Bar(_) = self.integrity_policy {
} else {
return Ok(());
}
// flow resumes here
or the equally awkward empty match block:
// If we are not explicitly using Bar, just return now
match self.integrity_policy {
Foo::Bar(_) => return Ok(());
_ => {}
}
// flow resumes here
It would be great if this were allowed:
// If we are not explicitly using Bar, just return now
if !let Foo::Bar(_) = self.integrity_policy {
return Ok(());
}
// flow resumes here
or perhaps a variation on that with slightly less accurate mathematical connotation but far clearer in its intent (you can't miss the ! this time):
// If we are not explicitly using Bar, just return now
if let Foo::Bar(_) != self.integrity_policy {
return Ok(());
}
// flow resumes here
(although perhaps it is a better idea to tackle this from an entirely different perspective with the goal of greatly increasing overall ergonomics with some form of is operator, e.g. if self.integrity_policy is Foo::Bar ..., but that is certainly a much more contentious proposition.)
or the equally awkward empty match block
I don't understand what's "awkward" in a block.
Furthermore, I don't see any good syntax for realizing this. Certainly, both proposed ones (if !let foo = … and if let foo != …) are much more awkward and a lot harder to read than a perfectly clear match. I would consider such code less ergonomic and less readable than the equivalent match expression.
We've seen numerous proposals for this, so maybe review them before attempting to push any serious discussion.
If the variants contain data then you normally require said data, but you cannot bind with a non-match, so is_[property] methods are frequently best at covering the actual station. If is_[property] methods do not provide a nice abstraction, then maybe all those empty match arms actually serve some purpose, but if not then you can always use a wild card:
let x = match self.integrity_policy {
Foo::Bar(x) => x,
_ => return Ok(()),
}
Also, one can always do very fancy comparisons like:
use std::mem::discriminant;
let d = discriminant(self.integrity_policy);
while d != discriminant(self.integrity_policy) { // loop until our state machine changes state
...
}
I believe the only "missing" syntax around bindings is tightly related to refinement types, which require a major type system extension. In my opinion, we should first understand more what design by contract and formal verification might look like in Rust because formal verification is currently the major use case for refinement types. Assuming no problems, there is a lovely syntax in which some refine keyword works vaguely like a partial match. As an example, let y = x? would be equivalent to
let Ok(y) = refine x { Err(z) => return z.into(); }
In this let Ok(y) = .. could type checks because refine returns a refinement type, specifically an enum variant type ala #2593. I suppose refinement is actually kinda the opposite of what you suggest here, but figured I'd mention it.
I looked around for past proposals regarding expanding the if let syntax, starting with the original if let rfc and issues referenced in the comments before opening this.
@burdges Thanks for sharing that info, I have some reading to do. But with regards to
if
is_[property]methods do not provide a nice abstraction, then maybe all those empty match arms actually serve some purpose
No, those are exactly what I would like, except they're not available for enum variants, i.e. for enum Foo { Bar(i8), Baz } there is no (automatically-created) Foo::is_bar(&self) method. It is in fact the absence of such an interface that required the use of if let or match.
One problem with the existing if let syntax is that it is a wholly unique expression masquerading as an if statement. It isn't natural to have an if statement you can't negate - the default expectation is that this is a boolean expression that may be treated the same as any other predicate in an if clause.
No, those are exactly what I would like, except they're not available for enum variants.
Oh, I think that can be fixed quite easily. They could be #[derive]d easily based on naming conventions. I'll try to write up an example implementation soon.
I'd suggest #[allow(non_snake_case)] for autogenerated one, so they look like
#[allow(non_snake_case)]
pub fn is_A(&self) { if let MyEnum::A = self { true } else { false } }
That said, if you have more than a couple variants then is_ methods might describe meaningful variants collections, not individual variants. We're talking about situations where you do not care about the variant's data after all.
In fact, you'd often want the or/| pattern like
let x = match self.integrity_policy {
Foo::A(x) | Foo::B(x,_) => x,
Foo::C { .. } | Foo::D => return Ok(()),
Foo::E(_) => panic!(),
}
I made a PoC implementation of the "generate is_XXX methods automatically" approach.
@H2CO3 This already exists on crates.io: https://crates.io/crates/derive_is_enum_variant and there's likely more complex variants too involving prisms/lenses and whatnot.
It seems to me however that generating a bunch of .is_$variant() methods is not a solution that scales well and that the need for these are due to the lack of a bool typed operation such as expr is pat (which could be let pat = expr... -- color of bikeshed...).
Fortunately, given or-patterns (https://github.com/rust-lang/rust/issues/54883) let chains (https://github.com/rust-lang/rust/issues/53667), and a trivial macro defined like so:
macro_rules! is { ($(x:tt)+) => { if $(x)+ { true } else { false } } }
we can write:
is!(let Some(E::Bar(x)) && x.some_condition() && let Other::Stuff = foo(x));
and the simpler version of this is:
is!(let E::Bar(..) = something)
// instead of: something.is_bar()
@Centril I'm glad it already exists in a production-ready version. Then OP can just use it without needing to wait for an implementation.
there's likely more complex variants too involving prisms/lenses and whatnot.
What do you exactly mean by this? AFAIK there aren't many kinds of enum variants in Rust. There are only unit, tuple, and struct variants. I'm unaware of special prism and/or lens support in Rust that would lead to the existence of other kinds of variants.
It seems to me however that generating a bunch of .is_$variant() methods is not a solution that scales well
I beg to differ. Since they are generated automatically, there's not much the user has to do… moreover the generated functions are trivial, there are O(number of variants) of them, and they can be annotated with #[inline] so that the binary size won't be bigger compared to manually-written matching or negated if-let.
Fortunately, given or-patterns [and] let chains
Those are very nice, and seem fairly powerful. I would be glad if we could indeed reuse these two new mechanisms plus macros in order to avoid growing the language even more.
@H2CO3
@Centril I'm glad it already exists in a production-ready version. Then OP can just use it without needing to wait for an implementation.
🎉
What do you exactly mean by this? AFAIK there aren't many kinds of enum variants in Rust. There are only unit, tuple, and struct variants. I'm unaware of special prism and/or lens support in Rust that would lead to the existence of other kinds of variants.
I found this a while back: https://docs.rs/refraction/0.1.2/refraction/ and it seemed like an interesting experiment; other solutions might be to generate .extract_Bar(): Option<TupleOfBarsFieldTypes> and then use ? + try { .. } + .and_then() pervasively. You can use .is_some() on that to get the answer to "was it of the expected variant".
I beg to differ. Since they are generated automatically, there's not much the user has to do… moreover the generated functions are trivial, there are
O(number of variants)of them, and they can be annotated with#[inline]so that the binary size won't be bigger compared to manually-written matching or negated if-let.
In a small crate I don't think it would pay off to use a derive macro like this; just compiling syn and quote seems too costly to get anyone to accept it. Another problem with the deriving strategy is that when you are working on a codebase (say rustc) and you want to check whether a value is of a certain variant, then you first need to go to the type's definition and add the derive macro; that can inhibit flow.
Those are very nice, and seem fairly powerful. I would be glad if we could indeed reuse these two new mechanisms plus macros in order to avoid growing the language even more.
Sure; this is indeed nice; but imo, it seems natural and useful to think of let pat = expr as an expression typed at bool which is true iff pat matches expr and false otherwise. In that case, if !let pat = expr { ... } is merely the composition of if !expr { ... } and let pat = expr.
I'm for this. It arguably reduces the semantic complexity of the language, and improves consistency, especially with let-chaining coming in.
Has @rust-lang/libs thought of bundling the is! macro with the language, given how common it is?
See also #1303.
Opposed. Not a big enough use-case to warrant extension at language level. Similar to there not being both while and do while loops, it can be done via numerous user-level escape hatches provided above.
It is respectfully nothing like the while vs do while situation. A while loop is one thing, and do while is another. An if statement already exists in the language with clearly defined semantics and permutations. This syntax reuses the if statement in name only, masquerading as a block of code while not actually sharing any of its features apart from reusing the same if keyword, with no reason why that can’t be fixed.
I regard if let the same way you do: as a random recycling of if somewhat out of context; I wouldn't have voted for its addition. But disliking it doesn't mean I think it needs to get more ways to mean something else yet again. It does not. If you dislike my analogy, you can substitute the analogy that we don't (and should not gain) a match-not expression.
(And definitely also not a guard-let or whatever Swift has. It has too many of these.)
Which is why I think let should become an actual boolean expression, albeit with special rules around scoping. That solves the “random recycling” problem and also enables if !let.
(and while this is admittedly both rude and off topic :\, after checking your recent posts, is there anything you’re not against?)
In Ruby exists unless operator where executes code if conditional is false. If the conditional is true, code specified in the else clause is executed.
It may be like
unless let Foo::Bar(_) = self.integrity_policy {
return Ok(());
}
I’ve always disliked unless operators in languages that have them. There is some cognitive overhead for me to deal with the extra implicit negation.
Hi,
I've landed here looking for if !let. I wanted to write:
if !let Ok((Index{num_mirs: 0}, None)) = Decoder::new(&mut curs) {
panic!();
}
Which I think today, is best expressed as:
match Decoder::new(&mut curs) {
Ok((Index{num_mirs: 0}, None)) => (),
_ => panic!(),
}
@mark-i-m I dislike them when they're just sugar for !, but if there's a difference in what they do (like the unless block must be : !), then it might be plausible. The negation, given the !-typed block, is consistent with things like assert!, so I don't think it's fundamentally confusing.
I feel like that would be a bit unexpected for most people. There is conceptually no reason unless foo {...} would not be a normal expression like if or match.
See https://github.com/rust-lang/rfcs/pull/1303
I feel like that would be a bit unexpected for most people. There is conceptually no reason
unless foo {...}would not be a normal expression likeiformatch.
AFAIK nobody is confused about guard statements in Swift.
The usage of a pattern in if !let Foo::Bar(_) = self.integrity_policy is extremely confusing to me. What if I don't ignore the content but use a name pattern? It wouldn't be visible in the block the follows as that is executed when the destructuring failed but the if also makes this a single pattern.
if !let Foo::Bar(policy) = self.integrity_policy else {
// Wait, `policy` is not a name here.
return Ok(policy);
}
Guard blocks as in #1303 don't have this problem.
@HeroicKatora I think you linked to the wrong RFC (I don't think you mean to link to supporting comments in rustdoc)
@KrishnaSannasi Indeed. Thanks.
I don't really like the different proposition of the if !let .. or if let Some(_) != ... they feel wrong to me but it still think there is a need for something like this.
Here my use case. it's a fake one but I have often encounter similar situation:
fn strange_function(real_unsecure_value:SomeType) -> u32
{
let x = real_unsecure_value;
if let Some(foo) = x.getFoo()
{
if let Some(bar) = foo.getBar()
{
if let Some(qux) = bar.getQux()
{
if qux.some_test()
{
return qux.some_calculus();
}
else
{
return 0;
}
}
else
{
return 1;
}
}
else
{
return 2;
}
}
else
{
return 3;
}
}
We can all agree this does not look pretty neither really readdable. What failed unwrapping does return 2 ? And we only have 4 tests. match will not really help us here.
Some general idea is fail fast. So instead of branching on success we do the opposite.
fn strange_function(real_unsecure_value:SomeType) -> u32
{
let x = real_unsecure_value;
if x.getFoo() == None { return 3; }
let foo = x.getFoo().unwrap();
if foo.getBar() == None { return 2; }
let bar = foo.getBar().unwrap();
if bar.getQux() == None { return 1; }
let qux = bar.getQux().unwrap();
if qux.someTest() == false { return 0; }
return qux.some_calculus();
}
This is much more readable, but there is useless unwrapping in between.
Here what I propose :
fn strange_function(real_unsecure_value:SomeType) -> u32
{
let x = real_unsecure_value;
guard let Some(foo) = x.getFoo() { return 3; }
guard let Some(bar) = foo.getBar() { return 2; }
guard let Some(qux) = bar.getQux() { return 1; }
if qux.someTest() == false { return 0; }
return qux.some_calculus();
}
I actually don't see why any special syntax is required here.
This is a perfectly valid C# code
int? obj = null;
if (!(obj is int i)) {
// int j = i; // CS0165 Use of unassigned local variable 'i'
return;
}
Console.WriteLine(i);
It's not very surprising that i is only allowed outside the block since you negated the condition. I think considering it confusing is a bit overthought.
I don't really like the different proposition of the
if !let ..orif let Some(_) != ...they feel wrong to me but it still think there is a need for something like this.Here my use case. it's a fake one but I have often encounter similar situation:
fn strange_function(real_unsecure_value:SomeType) -> u32 { let x = real_unsecure_value; if let Some(foo) = x.getFoo() { if let Some(bar) = foo.getBar() { if let Some(qux) = bar.getQux() { if qux.some_test() { return qux.some_calculus(); } else { return 0; } } else { return 1; } } else { return 2; } } else { return 3; } }We can all agree this does not look pretty neither really readdable. What failed unwrapping does return 2 ? And we only have 4 tests.
matchwill not really help us here.Some general idea is fail fast. So instead of branching on success we do the opposite.
fn strange_function(real_unsecure_value:SomeType) -> u32 { let x = real_unsecure_value; if x.getFoo() == None { return 3; } let foo = x.getFoo().unwrap(); if foo.getBar() == None { return 2; } let bar = foo.getBar().unwrap(); if bar.getQux() == None { return 1; } let qux = bar.getQux().unwrap(); if qux.someTest() == false { return 0; } return qux.some_calculus(); }This is much more readable, but there is useless unwrapping in between.
Here what I propose :
fn strange_function(real_unsecure_value:SomeType) -> u32 { let x = real_unsecure_value; guard let Some(foo) = x.getFoo() { return 3; } guard let Some(bar) = foo.getBar() { return 2; } guard let Some(qux) = bar.getQux() { return 1; } if qux.someTest() == false { return 0; } return qux.some_calculus(); }
I know someone who would like to have monads in Rust… :trollface:
Since it's bikeshedding time, I would like a blue one!
fn strange_function(real_unsecure_value:SomeType) -> u32
{
let x = real_unsecure_value;
let Some(foo) = x.getFoo() otherwise { return 3; }
let Some(bar) = foo.getBar() otherwise { return 2; }
let Some(qux) = bar.getQux() otherwise { return 1; }
if qux.someTest() == false { return 0; }
return qux.some_calculus();
}
It can also be chained easily
fn strange_function(real_unsecure_value:SomeType) -> u32
{
let x = real_unsecure_value;
let Some(foo) = x.getFoo() && Some(bar) = foo.getBar() otherwise { return 1; }
return bar.some_calculus();
}