summaryrefslogtreecommitdiffstats
path: root/tests/ui/let-else/let-else-deref-coercion.rs
blob: 052a5a8c73cc4ab05285ca5771735235bffa6ac5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
// Taken from https://github.com/rust-lang/rust/blob/6cc0a764e082d9c0abcf37a768d5889247ba13e2/compiler/rustc_typeck/src/check/_match.rs#L445-L462
//
// We attempt to `let Bar::Present(_) = foo else { ... }` where foo is meant to Deref/DerefMut to
// Bar. This fails, you must add a type annotation like `let _: &mut Bar = _ else { ... }`


use std::ops::{Deref, DerefMut};

struct Foo(Bar);

enum Bar {
    Present(u32),
    Absent,
}
impl Deref for Foo {
    type Target = Bar;
    fn deref(&self) -> &Bar {
        &self.0
    }
}
impl DerefMut for Foo {
    fn deref_mut(&mut self) -> &mut Bar {
        &mut self.0
    }
}
impl Bar {
    fn bar(&self) -> Option<u32> {
        let Bar::Present(z): &Bar = self else {
            return None;
        };
        return Some(*z);
    }
}
impl Foo {
    // Try without the type annotation
    fn set_bar_unannotated(&mut self, value: u32) {
        let Bar::Present(z) = self else { //~ ERROR mismatched types
            return;
        };
        *z = value;
    }
}

fn main() {
    let mut foo = Foo(Bar::Present(1));
    foo.set_bar_unannotated(54);
    assert_eq!(foo.bar(), Some(54));
    irrefutable::inner();
}

// The original, to show it fails for irrefutable let decls
mod irrefutable {
    use std::ops::{Deref, DerefMut};
    struct Foo(Bar);
    struct Bar(u32);
    impl Deref for Foo {
        type Target = Bar;
        fn deref(&self) -> &Bar {
            &self.0
        }
    }
    impl DerefMut for Foo {
        fn deref_mut(&mut self) -> &mut Bar {
            &mut self.0
        }
    }
    fn foo(x: &mut Foo) {
        let Bar(z) = x; //~ ERROR mismatched types
        *z = 54;
        assert_eq!((x.0).0, 54);
    }
    pub fn inner() {
        foo(&mut Foo(Bar(1)));
    }
}