Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Rust how do I pass a diverging function as parameter to another function

Tags:

rust

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?

like image 840
joegtp Avatar asked Dec 13 '25 08:12

joegtp


2 Answers

! 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.

See also

  • What is a crate attribute and where do I add it?
  • What is the stabilization process?
  • How to use nightly: Is it possible to have multiple coexisting Rust installations?
like image 112
trent Avatar answered Dec 16 '25 12:12

trent


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.

like image 39
Lukas Kalbertodt Avatar answered Dec 16 '25 12:12

Lukas Kalbertodt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!