Skip to content

Compile error with type mismatch in Fn() -> ! #129441

@Seidko

Description

@Seidko

I tried this code:

#![feature(never_type)]

fn main(){
    let vec = vec!["0"];
    let closure = || -> ! {
        dbg!(vec);
        panic!()
    };
    let s = vec.get(0).unwrap_or_else(closure);
}

playground link

I expected these code to compile.

Instead, I got type can not assign:

error[E0271]: expected `{[email protected]:5:19}` to be a closure that returns `&&str`, but it returns `!`
    --> src/main.rs:9:39
     |
9    |     let s = vec.get(0).unwrap_or_else(closure);
     |                        -------------- ^^^^^^^ expected `&&str`, found `!`
     |                        |
     |                        required by a bound introduced by this call
     |
     = note: expected reference `&&str`
                     found type `!`
note: required by a bound in `Option::<T>::unwrap_or_else`
    --> /playground/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/option.rs:1006:24
     |
1004 |     pub fn unwrap_or_else<F>(self, f: F) -> T
     |            -------------- required by a bound in this associated function
1005 |     where
1006 |         F: FnOnce() -> T,
     |                        ^ required by this bound in `Option::<T>::unwrap_or_else`

For more information about this error, try `rustc --explain E0271`.

The closure never return and we no need to care about it return and rust's never type can be assigned to any type in type theory.

Meta

rustc --version --verbose:

rustc 1.82.0-nightly (a32d4a0e8 2024-08-21)
binary: rustc
commit-hash: a32d4a0e822a29a6682e08b75a8df4c29c7fa9f1
commit-date: 2024-08-21
host: x86_64-unknown-linux-gnu
release: 1.82.0-nightly
LLVM version: 19.1.0

There are no backtrace output with RUST_BACKTRACE=1

Tracking:

Metadata

Metadata

Assignees

No one assigned

    Labels

    F-never_type`#![feature(never_type)]`

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions