Skip to content

Commit 79b7a9e

Browse files
committed
Auto merge of #29916 - Manishearth:diag-401, r=steveklabnik
None
2 parents 731c0ce + c23cbae commit 79b7a9e

File tree

1 file changed

+71
-1
lines changed

1 file changed

+71
-1
lines changed

src/librustc_resolve/diagnostics.rs

Lines changed: 71 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -273,6 +273,77 @@ on this topic:
273273
https://doc.rust-lang.org/reference.html#use-declarations
274274
"##,
275275

276+
E0401: r##"
277+
Inner functions do not inherit type parameters from the functions they are
278+
embedded in. For example, this will not compile:
279+
280+
```
281+
fn foo<T>(x: T) {
282+
fn bar(y: T) { // T is defined in the "outer" function
283+
// ..
284+
}
285+
bar(x);
286+
}
287+
```
288+
289+
Functions inside functions are basically just like top-level functions, except
290+
that they can only be called from the function they are in.
291+
292+
There are a couple of solutions for this.
293+
294+
You can use a closure:
295+
296+
```
297+
fn foo<T>(x: T) {
298+
let bar = |y: T| { // explicit type annotation may not be necessary
299+
// ..
300+
}
301+
bar(x);
302+
}
303+
```
304+
305+
or copy over the parameters:
306+
307+
```
308+
fn foo<T>(x: T) {
309+
fn bar<T>(y: T) {
310+
// ..
311+
}
312+
bar(x);
313+
}
314+
```
315+
316+
Be sure to copy over any bounds as well:
317+
318+
```
319+
fn foo<T: Copy>(x: T) {
320+
fn bar<T: Copy>(y: T) {
321+
// ..
322+
}
323+
bar(x);
324+
}
325+
```
326+
327+
This may require additional type hints in the function body.
328+
329+
In case the function is in an `impl`, defining a private helper function might
330+
be easier:
331+
332+
```
333+
impl<T> Foo<T> {
334+
pub fn foo(&self, x: T) {
335+
self.bar(x);
336+
}
337+
fn bar(&self, y: T) {
338+
// ..
339+
}
340+
}
341+
```
342+
343+
For default impls in traits, the private helper solution won't work, however
344+
closures or copying the parameters should still work.
345+
"##,
346+
276347
E0403: r##"
277348
Some type parameters have the same name. Example of erroneous code:
278349
@@ -909,7 +980,6 @@ register_diagnostics! {
909980
E0254, // import conflicts with imported crate in this module
910981
E0257,
911982
E0258,
912-
E0401, // can't use type parameters from outer function
913983
E0402, // cannot use an outer type parameter in this context
914984
E0406, // undeclared associated type
915985
E0408, // variable from pattern #1 is not bound in pattern #

0 commit comments

Comments
 (0)