Non-diverging functions work fine
fn test(f: &Fn() -> u8) {}
But I can't accept a diverging function like this
fn test_diverging(f: &Fn() -> !) {}
I get the following error
error[E0658]: The `!` type is experimental (see issue #35121)
--> examples/two_tasks.rs:44:31
|
44 | fn test_diverging(f: &Fn() -> !) {}
| ^
Looking at issue #35121 I could see how that might fix it but in the mean time is there a work around?
! in some contexts is still experimental, which means it's not available on the stable compiler (1.33 as of today). You can use it on the nightly compiler, but you have to opt-in explicitly to feature(never_type):
#![feature(never_type)]
fn test_diverging(f: &Fn() -> !) {}
(playground)
Be aware this means the feature may yet change before stabilization, so you're accepting the risk that a future compiler version will break your code.
Using the never type in functions and function pointer types is already stable. So if you don't need to use the Fn trait, you can just use this:
fn test_diverging(f: fn() -> !) {}
// ^ note the lowercase f
test_diverging(|| panic!("ouch"));
That way you can't pass closures that reference their environment, but non-capturing closures and standard functions work fine.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With