Skip to content

Improve E0401 diagnostics to mention other items #30253

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Dec 30, 2015
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 41 additions & 7 deletions src/librustc_resolve/diagnostics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -274,7 +274,7 @@ https://doc.rust-lang.org/reference.html#use-declarations
"##,

E0401: r##"
Inner functions do not inherit type parameters from the functions they are
Inner items do not inherit type parameters from the functions they are
embedded in. For example, this will not compile:

```
Expand All @@ -286,12 +286,32 @@ fn foo<T>(x: T) {
}
```

Functions inside functions are basically just like top-level functions, except
that they can only be called from the function they are in.
nor will this:

```
fn foo<T>(x: T) {
type MaybeT = Option<T>;
// ...
}
```

or this:

```
fn foo<T>(x: T) {
struct Foo {
x: T,
}
// ...
}
```

Items inside functions are basically just like top-level items, except
that they can only be used from the function they are in.

There are a couple of solutions for this.

You can use a closure:
If the item is a function, you may use a closure:

```
fn foo<T>(x: T) {
Expand All @@ -302,7 +322,7 @@ fn foo<T>(x: T) {
}
```

or copy over the parameters:
For a generic item, you can copy over the parameters:

```
fn foo<T>(x: T) {
Expand All @@ -313,6 +333,12 @@ fn foo<T>(x: T) {
}
```

```
fn foo<T>(x: T) {
type MaybeT<T> = Option<T>;
}
```

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's a lot of empty lines!

Be sure to copy over any bounds as well:

```
Expand All @@ -324,10 +350,18 @@ fn foo<T: Copy>(x: T) {
}
```

```
fn foo<T: Copy>(x: T) {
struct Foo<T: Copy> {
x: T,
}
}
```

This may require additional type hints in the function body.

In case the function is in an `impl`, defining a private helper function might
be easier:
In case the item is a function inside an `impl`, defining a private helper
function might be easier:

```
impl<T> Foo<T> {
Expand Down