From 97bf386e8e04e8267b706460602fb08046286f87 Mon Sep 17 00:00:00 2001 From: Jules Bertholet Date: Thu, 4 Jul 2024 10:59:53 -0400 Subject: [PATCH] `&` constrains inference --- text/3627-match-ergonomics-2024.md | 52 ++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) diff --git a/text/3627-match-ergonomics-2024.md b/text/3627-match-ergonomics-2024.md index 0e594dfec20..a56eec5cb3a 100644 --- a/text/3627-match-ergonomics-2024.md +++ b/text/3627-match-ergonomics-2024.md @@ -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, 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 { + 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