Skip to content

Unable to pass hook to panic::set_hook as a variable or without specifying type #84296

@ghost

Description

I tried this code:

use std::panic;

fn main() {
    let new_hook = Box::new(|_| {});
    panic::set_hook(new_hook);
}

I expected it to compile successfully.

Instead, this happened:

error[E0308]: mismatched types
 --> src/main.rs:5:21
  |
5 |     panic::set_hook(new_hook);
  |                     ^^^^^^^^ one type is more general than the other
  |
  = note: expected type `FnOnce<(&PanicInfo<'_>,)>`
             found type `FnOnce<(&PanicInfo<'_>,)>`
note: this closure does not fulfill the lifetime requirements
 --> src/main.rs:4:29
  |
4 |     let new_hook = Box::new(|_| {});
  |                             ^^^^^^

error: aborting due to previous error

For more information about this error, try `rustc --explain E0308`.
error: could not compile `playground`

To learn more, run the command again with --verbose.

If I however not assign the Box to a variable and instead directly pass it to panic::set_hook, it compiles:

use std::panic;

fn main() {
    panic::set_hook(Box::new(|_| {}));
}

I believe it should be allowed to assign it to a variable beforehand.

That, or if you explicitly specify the type, it compiles too:

use std::panic;

type Hook = Box<dyn Fn(&panic::PanicInfo<'_>) + Sync + Send + 'static>;

fn main() {
    let new_hook: Hook = Box::new(|_| {});
    panic::set_hook(new_hook);
}

I believe it should be able to infer the type on its own.

Meta

rustc --version --verbose:

rustc 1.51.0 (2fd73fabe 2021-03-23)
binary: rustc
commit-hash: 2fd73fabe469357a12c2c974c140f67e7cdd76d0
commit-date: 2021-03-23
host: x86_64-unknown-linux-gnu
release: 1.51.0
LLVM version: 11.0.1

Note that on beta and nightly the error is different.

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-lifetimesArea: Lifetimes / regionsC-discussionCategory: Discussion or questions that doesn't represent real issues.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

        Participants

        @ChrisDenton@fmease

        Issue actions

          Unable to pass hook to panic::set_hook as a variable or without specifying type · Issue #84296 · rust-lang/rust