[英]In Rust how do I pass a diverging function as parameter to another function
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? 看问题#35121我可以看到它可能如何解决它,但同时有一个解决方法?
!
in some contexts is still experimental, which means it's not available on the stable compiler (1.33 as of today). 在某些情况下仍然是实验性的,这意味着它在稳定的编译器上不可用(截至今天为1.33)。 You can use it on the nightly compiler, but you have to opt-in explicitly to
feature(never_type)
: 您可以在夜间编译器上使用它,但您必须明确选择
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. 使用never类型的函数和函数指针类型已经很稳定。 So if you don't need to use the
Fn
trait, you can just use this: 因此,如果您不需要使用
Fn
特征,您可以使用:
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. 这样你就无法传递引用其环境的闭包,但非捕获闭包和标准函数工作正常。
To use unstable feature you need to use nightly toolchain and active the desired unstable feature. 要使用不稳定的功能,您需要使用夜间工具链并激活所需的不稳定功能。
#![feature(never_type)]
fn test_diverging(f: &Fn() -> !) {}
See also: 也可以看看:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.