skip to content

In Rust, why does `fn min_len(n: usize) -> fn(&str) -> bool { move |s| s.len() >= n }` fail with E0308, and what fixes it?

level: middleimportance: should knowfreq 45%

answer

  1. lowercase fn is a type
  2. a code address with no data
  3. only non-capturing closures coerce
  4. opaque return or a boxed trait object

basics

~20 s

A fn pointer is a bare code address with no room for captured data, so only functions and non-capturing closures coerce to it. This closure captures n, so rustc reports mismatched types. Return impl Fn(&str) -> bool instead.

solid answer

~40 s

`fn(&str) -> bool` is a function pointer type: one code address, with nowhere to keep captured values. The Reference allows a coercion to it only from function items and non-capturing, non-async closures. `move |s| s.len() >= n` captures `n`, so it is a closure type that carries data, and rustc reports E0308 with the note "closures can only be coerced to `fn` types if they do not capture any variables". Return `impl Fn(&str) -> bool`, which hands back the concrete closure type without naming it, or `Box<dyn Fn(&str) -> bool>` when one function must return closures of different types. The same rule applies to storage: a `Vec<fn(&str) -> bool>` can hold named validators but not a rule that captures a limit, which needs `Vec<Box<dyn Fn(&str) -> bool>>`.

code

rust · 26 lines
rust
fn not_blank(s: &str) -> bool {
    !s.trim().is_empty()
}

fn min_len(n: usize) -> impl Fn(&str) -> bool {
    move |s| s.len() >= n
}

fn main() {
    // fn items and non-capturing closures coerce to a fn pointer
    let plain: Vec<fn(&str) -> bool> = vec![not_blank, |s| s.is_ascii()];

    // anything that captures needs a closure type: generic, impl Fn or dyn Fn
    let rules: Vec<Box<dyn Fn(&str) -> bool>> =
        vec![Box::new(not_blank), Box::new(min_len(3)), Box::new(min_len(8))];

    let input = "token";
    println!("{:?}", plain.iter().map(|f| f(input)).collect::<Vec<_>>());
    println!("{:?}", rules.iter().map(|f| f(input)).collect::<Vec<_>>());
    println!(
        "fn ptr {} B, closure {} B, fn item {} B",
        size_of::<fn(&str) -> bool>(),
        size_of_val(&min_len(3)),
        size_of_val(&not_blank),
    );
}

go deeper

for a junior

Recall that lowercase fn is a pointer type and only functions and closures that capture nothing coerce to it.

for a middle

Explain why captured data cannot fit in a function pointer, read the E0308 note, and fix a returned predicate with impl Fn or Box<dyn Fn>.

for a senior

Choose between fn pointers, generic bounds, impl Fn and boxed trait objects by weighing indirect calls, allocations, monomorphisation and what callers can pass in.

for a principal

In a public API, a fn parameter locks out every capturing closure for good; reserve it for C callbacks and static dispatch tables, and default to generic bounds.

## Two different things called fn Rust has a **function pointer type**, written with a lowercase `fn`, such as `fn(&str) -> bool`, and three **call traits**, `Fn`, `FnMut` and `FnOnce`. The standard library's doc comment for `Fn` warns that the trait "is not to be confused with function pointers (`fn`)". A function pointer is a type: a single machine address of code, the size of a pointer, `Copy`, and callable. A closure is a value of its own anonymous type that holds whatever it captured; it implements one or more of the call traits but is not itself a function pointer. | Value | Its type | Size on a 64-bit target | Implements the call traits | Coerces to `fn(&str) -> bool` | |---|---|---|---|---| | `not_blank`, a named `fn` item | a unique zero-sized fn item type | 0 bytes | all three | yes | | a `fn(&str) -> bool` variable | the function pointer type | 8 bytes | all three | it already is one | | `\|s: &str\| s.is_ascii()` | a unique closure type, nothing captured | 0 bytes | all three | yes | | `move \|s\| s.len() >= n` | a unique closure type holding `n` | 8 bytes, for one `usize` | per its body | **no** | The Reference states the coercion rule in one line: function pointers "can be created via a coercion from both function items and non-capturing, non-async closures". ## Why the capture breaks the coercion A function pointer has nowhere to store `n`. If rustc turned the closure into a bare code address, the code would run with no access to the value it needs. So the coercion is refused and the return expression keeps its closure type, which does not match the declared return type. rustc 1.99 reports: - **E0308**, "mismatched types", "expected fn pointer, found closure"; - a note, "closures can only be coerced to `fn` types if they do not capture any variables", pointing at `n`; - a help line suggesting the return type `impl Fn(&'_ str) -> bool`. The same E0308 and the same note appear when you `push` a capturing closure into a `Vec<fn(&str) -> bool>`. ## The fixes for a configured predicate 1. **`-> impl Fn(&str) -> bool`.** The function returns its concrete closure type, unnamed. There is no allocation and no indirect call, and the caller can call it, store it in a generic field or pass it to anything bounded by `Fn`, `FnMut` or `FnOnce`. The `move` keeps `n` inside the closure, which must outlive the call to `min_len`. 2. **`-> Box<dyn Fn(&str) -> bool>`.** The closure is boxed and called through a vtable. This is needed when one function returns different closures on different paths, or when the result goes into a collection with others. 3. **Take the predicate generically on the input side**, as `F: Fn(&str) -> bool`, so callers can pass a named function, a non-capturing closure or a capturing one. Because function items and safe function pointers implement all three call traits, a generic bound accepts every kind of callable, while a `fn` parameter accepts only the non-capturing ones. Each closure has its own type, so two `impl Fn` results from different functions still cannot share a plain `Vec`; that is the lesson on `impl Trait` returns. For a list of rules, `Vec<Box<dyn Fn(&str) -> bool>>` is the usual answer. ## When a fn pointer is the right type - **Callbacks into C**, which has no closures and expects a plain address; the material on calling foreign functions covers the `extern "C"` side. - **Static tables of operations**, such as a dispatch table indexed by an opcode, where every entry is a named function and the table can be a `const` or a `static`. - **Avoiding monomorphisation**: a `fn` parameter compiles the callee once instead of once per closure type, at the price of an indirect call. - Values that must be `Copy` and pointer-sized whatever they point to. ## Mistakes to avoid - Writing `fn(...)` as a return type for a closure that captures configuration. - Assuming `move` lets a closure coerce; moving `n` in is exactly what gives the closure data a pointer cannot hold. - Taking `fn` parameters in a general-purpose API, which locks out every capturing closure callers might pass.

  • Why does a parameter `F: Fn(&str) -> bool` accept a named function as well as a capturing closure?
    Because function items and safe function pointers implement `Fn`, `FnMut` and `FnOnce`. The generic parameter is instantiated with the function's own zero-sized item type, so the call is direct. A `fn(&str) -> bool` parameter, by contrast, accepts only callables with no captures.
  • When must `min_len` return `Box<dyn Fn(&str) -> bool>` rather than `impl Fn`?
    When the function can return closures of different concrete types, for example a different closure on each branch, because `impl Fn` stands for exactly one type. It is also the usual choice when the result is stored beside other rules in one collection, at the cost of an allocation and an indirect call.

  • A move closure can coerce to a fn pointer because it owns its data.
  • fn(&str) -> bool and Fn(&str) -> bool name the same thing.
  • A capturing closure is just a fn pointer plus a hidden global.
  • Use fn parameters everywhere because they are cheaper than generics.
  • Function pointers do not implement the Fn traits.