]> git.lizzy.rs Git - rust.git/blob - tests/ui/suggestions/lifetimes/missing-lifetimes-in-signature.rs
Make const/fn return params more suggestable
[rust.git] / tests / ui / suggestions / lifetimes / missing-lifetimes-in-signature.rs
1 pub trait Get<T> {
2     fn get(self) -> T;
3 }
4
5 struct Foo {
6     x: usize,
7 }
8
9 impl Get<usize> for Foo {
10     fn get(self) -> usize {
11         self.x
12     }
13 }
14
15 fn foo<G, T>(g: G, dest: &mut T) -> impl FnOnce()
16 where
17     G: Get<T>,
18 {
19     move || {
20         //~^ ERROR hidden type for `impl FnOnce()` captures lifetime
21         *dest = g.get();
22     }
23 }
24
25 // After applying suggestion for `foo`:
26 fn bar<G, T>(g: G, dest: &mut T) -> impl FnOnce() + '_
27 where
28     G: Get<T>,
29 {
30     move || {
31         //~^ ERROR the parameter type `G` may not live long enough
32         *dest = g.get();
33     }
34 }
35
36 // After applying suggestion for `bar`:
37 fn baz<G: 'a, T>(g: G, dest: &mut T) -> impl FnOnce() + '_
38 //~^ ERROR undeclared lifetime name `'a`
39 where
40     G: Get<T>,
41 {
42     move || {
43         *dest = g.get();
44     }
45 }
46
47 // After applying suggestion for `baz`:
48 fn qux<'a, G: 'a, T>(g: G, dest: &mut T) -> impl FnOnce() + '_
49 where
50     G: Get<T>,
51 {
52     move || {
53         //~^ ERROR the parameter type `G` may not live long enough
54         *dest = g.get();
55     }
56 }
57
58 // Same as above, but show that we pay attention to lifetime names from parent item
59 impl<'a> Foo {
60     fn qux<'b, G: Get<T> + 'b, T>(g: G, dest: &mut T) -> impl FnOnce() + '_ {
61         move || {
62             //~^ ERROR the parameter type `G` may not live long enough
63             *dest = g.get();
64         }
65     }
66 }
67
68 // After applying suggestion for `qux`:
69 fn bat<'a, G: 'a, T>(g: G, dest: &mut T) -> impl FnOnce() + '_ + 'a
70 where
71     G: Get<T>,
72 {
73     move || {
74         //~^ ERROR the parameter type `G` may not live long enough
75         //~| ERROR explicit lifetime required
76         *dest = g.get();
77     }
78 }
79
80 // Potential incorrect attempt:
81 fn bak<'a, G, T>(g: G, dest: &'a mut T) -> impl FnOnce() + 'a
82 where
83     G: Get<T>,
84 {
85     move || {
86         //~^ ERROR the parameter type `G` may not live long enough
87         *dest = g.get();
88     }
89 }
90
91 // We need to tie the lifetime of `G` with the lifetime of `&mut T` and the returned closure:
92 fn ok<'a, G: 'a, T>(g: G, dest: &'a mut T) -> impl FnOnce() + 'a
93 where
94     G: Get<T>,
95 {
96     move || {
97         *dest = g.get();
98     }
99 }
100
101 // This also works. The `'_` isn't necessary but it's where we arrive to following the suggestions:
102 fn ok2<'a, G: 'a, T>(g: G, dest: &'a mut T) -> impl FnOnce() + '_ + 'a
103 where
104     G: Get<T>,
105 {
106     move || {
107         *dest = g.get();
108     }
109 }
110
111 fn main() {}