Rust errors / Types and traits
Rust compiler error · checked with rustc 1.99.0
Rust error E0401: can't use generic parameters from outer item
What it meansInner items do not inherit the generic parameters from the items they are embedded in.
What rustc prints
error[E0401]: can't use generic parameters from outer item --> main.rs:2:15 | 1 | fn foo<T>(x: T) { | - type parameter from outer item 2 | fn bar(y: T) { // T is defined in the "outer" function | --- ^ use of generic parameter from outer item | | | generic parameter used in this inner function | = note: nested items are independent from their parent item for everything except for privacy and name resolution help: try introducing a local generic parameter here | 2 | fn bar<T>(y: T) { // T is defined in the "outer" function | +++
Real output of rustc 1.99.0 compiling the official example below (2021 edition). Your names and line numbers will differ; the first line is the part to match.
The compiler team's explanation
Inner items do not inherit the generic parameters from the items they are embedded in.
Erroneous code example:
fn foo<T>(x: T) {
fn bar(y: T) { // T is defined in the "outer" function
// ..
}
bar(x);
}
Nor will this:
fn foo<T>(x: T) {
type MaybeT = Option<T>;
// ...
}
Or this:
fn foo<T>(x: T) {
struct Foo {
x: T,
}
// ...
}
Items nested inside other items are basically just like top-level items, except that they can only be used from the item they are in.
There are a couple of solutions for this.
If the item is a function, you may use a closure:
fn foo<T>(x: T) {
let bar = |y: T| { // explicit type annotation may not be necessary
// ..
};
bar(x);
}
For a generic item, you can copy over the parameters:
fn foo<T>(x: T) {
fn bar<T>(y: T) {
// ..
}
bar(x);
}
fn foo<T>(x: T) {
type MaybeT<T> = Option<T>;
}
Be sure to copy over any bounds as well:
fn foo<T: Copy>(x: T) {
fn bar<T: Copy>(y: T) {
// ..
}
bar(x);
}
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 item is a function inside an impl, defining a private helper function might be easier:
impl<T> Foo<T> {
pub fn foo(&self, x: T) {
self.bar(x);
}
fn bar(&self, y: T) {
// ..
}
}
For default impls in traits, the private helper solution won't work, however closures or copying the parameters should still work.
From rustc --explain E0401 (1.99.0), part of the Rust project, MIT or Apache-2.0. Official page.
Related errors
- E0308mismatched types
- E0277the trait bound is not satisfied
- E0599no method named X found in the current scope
- E0433failed to resolve
- E0391cycle detected when computing the super clauses of `FirstTrait`
- E0393the type parameter `T` must be explicitly specified
- E0403the name `T` is already used for a generic parameter in this item's generic parameters
- E0404expected trait, found struct `Foo`
Up next
Often hit nextE0308: mismatched typesA related error from the same family.Read it next →Did this answer your question?