Skip to content

fn item can't coerce to trait object when a trait bound has a lifetime parameter #69994

@Ralith

Description

@Ralith
trait Trait<'a> {}
impl<'a, T> Trait<'a> for T {}

fn func<'a, T: Trait<'a>>(x: &'a str) {}
const CONST: &dyn for<'a> Fn(&'a str) = &func::<i32>;

fails to typecheck with the errors:

error[E0631]: type mismatch in function arguments
 --> src/lib.rs:5:41
  |
4 | fn func<'a, T: Trait<'a>>(x: &'a str) {}
  | ------------------------------------- found signature of `fn(&str) -> _`
5 | const CONST: &dyn for<'a> Fn(&'a str) = &func::<i32>;
  |                                         ^^^^^^^^^^^^ expected signature of `for<'a> fn(&'a str) -> _`
  |
  = note: required for the cast to the object type `dyn for<'a> std::ops::Fn(&'a str)`

error[E0271]: type mismatch resolving `for<'a> <fn(&str) {func::<'_, i32>} as std::ops::FnOnce<(&'a str,)>>::Output == ()`
 --> src/lib.rs:5:41
  |
5 | const CONST: &dyn for<'a> Fn(&'a str) = &func::<i32>;
  |                                         ^^^^^^^^^^^^ expected bound lifetime parameter 'a, found concrete lifetime
  |
  = note: required for the cast to the object type `dyn for<'a> std::ops::Fn(&'a str)`

If Trait does not have a lifetime parameter, or if func::<i32> is replaced with |x| func::<i32>(x), the example compiles successfully.

Meta

rustc --version --verbose:

rustc 1.42.0 (b8cedc004 2020-03-09)
binary: rustc
commit-hash: b8cedc00407a4c56a3bda1ed605c6fc166655447
commit-date: 2020-03-09
host: x86_64-unknown-linux-gnu
release: 1.42.0
LLVM version: 9.0

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-coercionsArea: implicit and explicit `expr as Type` coercionsA-lifetimesArea: Lifetimes / regionsC-bugCategory: This is a bug.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.T-langRelevant to the language team

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions