]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_error_codes/src/error_codes/E0401.md
Rollup merge of #93556 - dtolnay:trailingcomma, r=cjgillot
[rust.git] / compiler / rustc_error_codes / src / error_codes / E0401.md
1 Inner items do not inherit type or const parameters from the functions
2 they are embedded in.
3
4 Erroneous code example:
5
6 ```compile_fail,E0401
7 fn foo<T>(x: T) {
8     fn bar(y: T) { // T is defined in the "outer" function
9         // ..
10     }
11     bar(x);
12 }
13 ```
14
15 Nor will this:
16
17 ```compile_fail,E0401
18 fn foo<T>(x: T) {
19     type MaybeT = Option<T>;
20     // ...
21 }
22 ```
23
24 Or this:
25
26 ```compile_fail,E0401
27 fn foo<T>(x: T) {
28     struct Foo {
29         x: T,
30     }
31     // ...
32 }
33 ```
34
35 Items inside functions are basically just like top-level items, except
36 that they can only be used from the function they are in.
37
38 There are a couple of solutions for this.
39
40 If the item is a function, you may use a closure:
41
42 ```
43 fn foo<T>(x: T) {
44     let bar = |y: T| { // explicit type annotation may not be necessary
45         // ..
46     };
47     bar(x);
48 }
49 ```
50
51 For a generic item, you can copy over the parameters:
52
53 ```
54 fn foo<T>(x: T) {
55     fn bar<T>(y: T) {
56         // ..
57     }
58     bar(x);
59 }
60 ```
61
62 ```
63 fn foo<T>(x: T) {
64     type MaybeT<T> = Option<T>;
65 }
66 ```
67
68 Be sure to copy over any bounds as well:
69
70 ```
71 fn foo<T: Copy>(x: T) {
72     fn bar<T: Copy>(y: T) {
73         // ..
74     }
75     bar(x);
76 }
77 ```
78
79 ```
80 fn foo<T: Copy>(x: T) {
81     struct Foo<T: Copy> {
82         x: T,
83     }
84 }
85 ```
86
87 This may require additional type hints in the function body.
88
89 In case the item is a function inside an `impl`, defining a private helper
90 function might be easier:
91
92 ```
93 # struct Foo<T>(T);
94 impl<T> Foo<T> {
95     pub fn foo(&self, x: T) {
96         self.bar(x);
97     }
98
99     fn bar(&self, y: T) {
100         // ..
101     }
102 }
103 ```
104
105 For default impls in traits, the private helper solution won't work, however
106 closures or copying the parameters should still work.