Skip to content

Commit

Permalink
& constrains inference
Browse files Browse the repository at this point in the history
  • Loading branch information
Jules-Bertholet committed Jul 4, 2024
1 parent 27717e6 commit 97bf386
Showing 1 changed file with 52 additions and 0 deletions.
52 changes: 52 additions & 0 deletions text/3627-match-ergonomics-2024.md
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,58 @@ let &ref mut foo = &mut 42;
let _: &mut u8 = foo;
```

However, if the type of the scrutinee is unknown, an `&` pattern will still
constrain inference to force it to be a shared reference.

```rust
//! All editions
fn generic<R: Ref>() -> (R, bool) {
R::meow()
}

trait Ref: Sized {
fn meow() -> (Self, bool);
}

impl Ref for &'static [(); 0] {
fn meow() -> (Self, bool) {
(&[], false)
}
}

impl Ref for &'static mut [(); 0] {
fn meow() -> (Self, bool) {
(&mut [], true)
}
}

fn main() {
let (&_, b) = generic();
assert!(!b);
}
```

```rust
//! All editions
fn generic<R: Ref>() -> R {
R::meow()
}

trait Ref: Sized {
fn meow() -> Self;
}

impl Ref for &'static mut [(); 0] {
fn meow() -> Self {
&mut []
}
}

fn main() {
let &_ = generic(); //~ERROR[E0277]: the trait bound `&_: Ref` is not satisfied
}
```

## Edition 2024: `&` and `&mut` can match against inherited references

When the default binding mode is `ref` or `ref mut`, `&` and `&mut` patterns can
Expand Down

0 comments on commit 97bf386

Please sign in to comment.