In Rust, what changes when `impl Trait` moves from a function parameter to its return type, and who chooses the concrete type?
answer
- direction of choice
- anonymous generic parameter
- no turbofish for it
- body picks, caller sees bound
basics
~20 sIn a parameter, impl Trait is an anonymous generic: the caller picks the type and the function is monomorphized per type. In the return type, the function body picks one hidden type and the caller sees only the trait.
solid answer
~40 s`fn f(x: impl Trait)` is sugar for `fn f<T: Trait>(x: T)` with an unnamed `T`: the caller chooses the type by what it passes, each type gets its own monomorphized copy, and the body may use only `Trait`'s methods. Because the parameter has no name, callers cannot turbofish it; `show::<i32>(5)` fails with E0107. `fn f() -> impl Trait` reverses the direction: the body chooses one concrete type and the caller sees an opaque type with only `Trait`'s methods. That differs from `fn f<T: Trait>() -> T`, where the caller chooses `T` and the body must work for every `T`, which is why returning `5u8` from it fails with E0308.
code
rust · 25 linesuse std::fmt::Display;
fn log_all(items: impl IntoIterator<Item = impl Display>) {
for item in items {
println!("- {item}");
}
}
fn log_as<T: Display>(label: T, items: impl IntoIterator<Item = u8>) {
for item in items {
println!("{label}: {item}");
}
}
fn default_ids() -> impl Iterator<Item = u32> {
1..=3
}
fn main() {
log_all(vec!["a", "b"]);
log_all([1.5, 2.5]);
log_as::<&str>("byte", [7u8, 9]);
let ids: Vec<u32> = default_ids().collect();
println!("{ids:?}");
}go deeper
Recall that impl Trait in a parameter accepts any type implementing the trait, and in a return type hides the concrete type the function picked.
Explain the direction of choice: caller picks in argument position, the body picks in return position. Contrast -> impl Trait with a generic -> T and name the E0107 turbofish error.
Pick between named generics and impl Trait by whether the type repeats, needs a where clause or must be turbofished, and know that switching forms can break callers.
For a public API, prefer a named generic where callers may need to specify the type, and an opaque return where you want freedom to change the implementation.
## Two features behind one keyword Rust's `impl Trait` syntax means two different things depending on where it sits in a function signature. The Rust Reference calls them **anonymous type parameters** (argument position) and **abstract return types** (return position). The difference that interviewers probe is a single question: **who chooses the concrete type?** | | Argument position `fn f(x: impl Trait)` | Return position `fn f() -> impl Trait` | |---|---|---| | Who picks the type | the **caller**, by what it passes | the **function body** | | Equivalent to | `fn f<T: Trait>(x: T)` with an unnamed `T` | no generic equivalent; an opaque type | | Copies of the function | one per concrete argument type (monomorphization) | one hidden type per set of generic arguments | | Turbofish | not allowed for the anonymous parameter | not applicable | | What the other side sees | the body sees only `Trait`'s methods | the caller sees only `Trait`'s methods | ## Argument position: an anonymous generic `fn log_all(items: impl IntoIterator<Item = impl Display>)` is sugar for a generic function with two unnamed type parameters. Each call with a new argument type instantiates a new copy, exactly as `<T: Trait>` would. Two consequences follow: - The parameter has **no name**, so it cannot be referred to elsewhere in the signature. Two `impl Display` parameters are two independent types; if both arguments must have the same type, write `<T: Display>(a: T, b: T)`. - Callers cannot supply it with a turbofish. On rustc 1.99, `show::<i32>(5)` against `fn show(x: impl Display)` fails with **E0107**, "function takes 0 generic arguments but 1 generic argument was supplied", with the note "`impl Trait` cannot be explicitly specified as a generic argument". Named generic parameters in the same function can still be given explicitly, as in `log_as::<&str>(...)`. The Reference notes that switching a parameter between `<T: Trait>` and `impl Trait` **changes the number of generic arguments**, so it can break callers who used a turbofish. ## Return position: the function decides `fn default_ids() -> impl Iterator<Item = u32>` returns one concrete type that the body picks (here `RangeInclusive<u32>`), and the caller may use only the `Iterator` methods. Compare it with a generic return type: ```rust fn pick<T: Default>() -> T { T::default() } // caller chooses T fn ids() -> impl Iterator<Item = u32> { 1..=3 } // body chooses ``` With `pick`, the **caller** decides what `T` is (`let n: u8 = pick();`), and the body must work for every possible `T`. That is why `fn wrong<T: Display>() -> T { 5u8 }` fails with **E0308**: rustc explains "the caller chooses a type for `T` which can be different from `u8`" and suggests "consider using an impl return type". With `ids`, the body has already chosen; `let r: RangeInclusive<u32> = ids();` fails with E0308 because the caller sees only "opaque type `impl Iterator<Item = u32>`". ## Dispatch is static in both positions Neither position involves a trait object. In argument position the compiler generates one copy of the function per concrete argument type, so a call on the parameter inside the body is a direct, inlinable call. In return position the hidden type is one concrete type the compiler knows, so calls on the returned value are resolved at compile time unless the body chose to return a trait object as that type. The only thing `impl Trait` hides is the **name** of a type from one side of the call; the syntax itself adds no vtable and no allocation. That is the key contrast with `&dyn Trait` and `Box<dyn Trait>`, which erase the type at run time. ## Choosing between them 1. Take `impl Trait` in argument position when the parameter appears once and callers never need to name its type; it reads like an interface parameter and still compiles to static dispatch. 2. Use a named `<T: Trait>` when the type appears more than once, when a `where` clause needs it, or when callers should be able to turbofish it. 3. Return `impl Trait` when the concrete type is long, unnameable (closures, adapter chains) or an implementation detail you want freedom to change. 4. Return a generic `T` only when the caller genuinely selects the result type, as `str::parse` and `Iterator::collect` do. ## Common confusions - "Argument-position `impl Trait` is a trait object": it is not; it is monomorphized like any generic. - "Return-position `impl Trait` is the same as `-> T`": the direction of choice is reversed. - "The caller can treat the returned value as its hidden type": the opaque type exposes only its bounds, which is what lets the author change the body later.
- In Rust, are two `impl Display` parameters in one signature the same type?No. Each argument-position `impl Trait` introduces its own anonymous type parameter, so `fn pair(a: impl Display, b: impl Display)` accepts an `i32` and a `&str` together. When both arguments must share one type, write a named parameter: `fn pair<T: Display>(a: T, b: T)`.
- In Rust, can changing `fn f<T: Trait>(x: T)` to `fn f(x: impl Trait)` break callers?Yes. The Rust Reference notes that switching between the two forms changes the number of generic arguments. Any caller that wrote `f::<Concrete>(x)` stops compiling, because the anonymous parameter cannot be supplied explicitly; rustc 1.99 reports E0107. Callers that let inference choose are unaffected.
- Argument-position impl Trait is a trait object with dynamic dispatch
- Return-position impl Trait lets the caller choose the type
- fn f() -> impl Trait is the same as fn f<T: Trait>() -> T
- Callers can turbofish an impl Trait parameter like a named generic
- Two impl Display parameters must be the same concrete type