Skip to content

Box<dyn FnOnce(T)> doesn't seem to be really contravariant with T #100728

Description

@fakedrake

I tried this code:

type F<'arg> = Box<dyn FnOnce(&'arg ())>;
fn contravar<'small, 'large: 'small>(f: F<'small>) -> F<'large> {
    f
}

I expected it to compile but I got the following:

error: lifetime may not live long enough
 --> src/lib.rs:3:5
  |
2 | fn contravar<'small, 'large: 'small>(f: F<'small>) -> F<'large> {
  |              ------  ------ lifetime `'large` defined here
  |              |
  |              lifetime `'small` defined here
3 |     f
  |     ^ function was supposed to return data with lifetime `'large` but it is returning data with lifetime `'small`
  |
  = help: consider adding the following bound: `'small: 'large`

playground

$ rustc --version --verbose
rustc 1.65.0-nightly (29e4a9ee0 2022-08-10)
binary: rustc
commit-hash: 29e4a9ee0253cd39e552a77f51f11f9a5f1c41e6
commit-date: 2022-08-10
host: x86_64-unknown-linux-gnu
release: 1.65.0-nightly
LLVM version: 14.0.6
`rustc --version --verbose`:

I asked this on stackoverflow too hopefully I am not misinterpreting something about variance.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-dyn-traitArea: trait objects, vtable layoutA-trait-systemArea: Trait systemA-varianceArea: Variance (https://doc.rust-lang.org/nomicon/subtyping.html)C-bugCategory: This is a bug.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.T-typesRelevant to the types team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions