diff options
| author | Esteban Küber <esteban@kuber.com.ar> | 2024-01-29 20:34:29 +0000 | 
|---|---|---|
| committer | Esteban Küber <esteban@kuber.com.ar> | 2024-02-06 03:53:06 +0000 | 
| commit | a939bad513e6201d7be76c13080fc0cc901bd658 (patch) | |
| tree | defedaf66ee6bfb889074af88fdf8140f76259e3 /tests/ui/binding/irrefutable-if-let-without-else.rs | |
| parent | bf3c6c5bed498f41ad815641319a1ad9bcecb8e8 (diff) | |
| download | rust-a939bad513e6201d7be76c13080fc0cc901bd658.tar.gz rust-a939bad513e6201d7be76c13080fc0cc901bd658.zip | |
Suggest turnging `if let` into irrefutable `let` if appropriate
When encountering an `if let` tail expression without an `else` arm for an
enum with a single variant, suggest writing an irrefutable `let` binding
instead.
```
error[E0317]: `if` may be missing an `else` clause
  --> $DIR/irrefutable-if-let-without-else.rs:8:5
   |
LL |   fn foo(x: Enum) -> i32 {
   |                      --- expected `i32` because of this return type
LL | /     if let Enum::Variant(value) = x {
LL | |         value
LL | |     }
   | |_____^ expected `i32`, found `()`
   |
   = note: `if` expressions without `else` evaluate to `()`
   = help: consider adding an `else` block that evaluates to the expected type
help: consider using an irrefutable `let` binding instead
   |
LL ~     let Enum::Variant(value) = x;
LL ~         value
   |
```
Fix #61788.
Diffstat (limited to 'tests/ui/binding/irrefutable-if-let-without-else.rs')
| -rw-r--r-- | tests/ui/binding/irrefutable-if-let-without-else.rs | 28 | 
1 files changed, 28 insertions, 0 deletions
| diff --git a/tests/ui/binding/irrefutable-if-let-without-else.rs b/tests/ui/binding/irrefutable-if-let-without-else.rs new file mode 100644 index 00000000000..5aaf4ace3f8 --- /dev/null +++ b/tests/ui/binding/irrefutable-if-let-without-else.rs @@ -0,0 +1,28 @@ +// run-rustfix +enum Enum { + Variant(i32), +} +struct Struct(i32); + +fn foo(x: Enum) -> i32 { + if let Enum::Variant(value) = x { //~ ERROR `if` may be missing an `else` clause + value + } +} +fn bar(x: Enum) -> i32 { + if let Enum::Variant(value) = x { //~ ERROR `if` may be missing an `else` clause + let x = value + 1; + x + } +} +fn baz(x: Struct) -> i32 { + if let Struct(value) = x { //~ ERROR `if` may be missing an `else` clause + let x = value + 1; + x + } +} +fn main() { + let _ = foo(Enum::Variant(42)); + let _ = bar(Enum::Variant(42)); + let _ = baz(Struct(42)); +} | 
