noib3
November 6, 2022, 3:34pm
1
I'm trying to understand why this code shouldn't compile:
enum Foo<'a, T> {
A,
B(T),
C(&'a T),
}
fn main() {
let foo = Foo::<'static, ()>::A;
match foo {
Foo::A => {},
Foo::B(ref t) | Foo::C(t) => todo!(),
}
}
isn't t
bound to an &T
in both cases? This more verbose version works just fine:
fn main() {
let foo = Foo::<'static, ()>::A;
let t = match foo {
Foo::A => return,
Foo::B(ref t) => t,
Foo::C(t) => t,
};
todo!()
}
Link to a playground .
2 Likes
trentj
November 6, 2022, 3:57pm
2
t
has to be bound the same way in all alternatives joined with |
. I'm not sure if there is a "real" reason for this or if it's a consequence of how pattern ergonomics works, or something else, but you can work around it (at least in this case) by matching
Foo::B(ref t) | Foo::C(&ref t) => ...
// ^^^^^
It could use a better error message, but the reason is because they have different lifetimes. When you match it separately, that gives it a chance for variance to coerce the lifetime shorter. You can force C
to reborrow with &(ref t)
.
7 Likes
I filed a diagnostic issue:
opened 08:57PM - 06 Nov 22 UTC
A-diagnostics
T-compiler
From https://users.rust-lang.org/t/how-to-match-t-and-t-in-the-same-arm/83835
…
Given the following code: [playground](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=720f081ede76833bd2299d7eecfb7dbd)
```rust
enum Foo<'a, T> {
A,
B(T),
C(&'a T),
}
fn main() {
let foo = Foo::<'static, ()>::A;
match foo {
Foo::A => {},
Foo::B(ref t) | Foo::C(t) => todo!(),
}
}
```
The current output is:
```
error[E0409]: variable `t` is bound inconsistently across alternatives separated by `|`
--> src/main.rs:12:32
|
12 | Foo::B(ref t) | Foo::C(t) => todo!(),
| - ^ bound in different ways
| |
| first binding
```
The cause of the error is a lifetime difference, where `B(ref t)` binds `&'_ T` (for some local lifetime) and `C(t)` binds `&'static T`. It would be nice to have a hint about this, possibly suggesting a fix into `C(&ref t)` to reborrow that reference.
(Even better if the language/compiler could make that happen automatically!)
3 Likes
system
Closed
February 4, 2023, 8:58pm
5
This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.