非分散功能可以正常工作
fn test(f: &Fn() -> u8) {}
Run Code Online (Sandbox Code Playgroud)
但是我不能接受这样的分歧功能
fn test_diverging(f: &Fn() -> !) {}
Run Code Online (Sandbox Code Playgroud)
我收到以下错误
error[E0658]: The `!` type is experimental (see issue #35121)
--> examples/two_tasks.rs:44:31
|
44 | fn test_diverging(f: &Fn() -> !) {}
| ^
Run Code Online (Sandbox Code Playgroud)
查看问题#35121,我可以看到如何解决该问题,但与此同时可以解决此问题?
! 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() -> !) {}
Run Code Online (Sandbox Code Playgroud)
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.
使用Never类型的函数和函数指针类型已经很稳定。因此,如果您不需要使用该Fn特征,则可以使用以下特征:
fn test_diverging(f: fn() -> !) {}
// ^ note the lowercase f
test_diverging(|| panic!("ouch"));
Run Code Online (Sandbox Code Playgroud)
这样,您就不能传递引用其环境的闭包,但是非捕获闭包和标准函数可以正常工作。