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