非分歧函数工作正常
fn test(f: &Fn() -> u8) {}
但我无法接受这样的分歧功能
fn test_diverging(f: &Fn() -> !) {}
我收到以下错误
error[E0658]: The `!` type is experimental (see issue #35121)
--> examples/two_tasks.rs:44:31
|
44 | fn test_diverging(f: &Fn() -> !) {}
| ^
看看issue #35121我可以看到它可能如何解决它,但同时还有一个解决方法吗?
!
在某些情况下仍然是实验性的,这意味着它在稳定的编译器上不可用(截至今天为1.33)。你可以在夜间编译器上使用它,但你必须明确地选择加入feature(never_type)
:
#![feature(never_type)]
fn test_diverging(f: &Fn() -> !) {}
(Qazxswpoi)
请注意,这意味着该功能可能会在稳定之前发生变化,因此您将接受将来的编译器版本将破坏您的代码的风险。
使用never类型的函数和函数指针类型已经很稳定。因此,如果您不需要使用Is it possible to have multiple coexisting Rust installations?特性,您可以使用:
Fn
这样你就无法传递引用其环境的闭包,但非捕获闭包和标准函数工作正常。
如果你想保持稳定,你可以使用fn test_diverging(f: fn() -> !) {}
// ^ note the lowercase f
test_diverging(|| panic!("ouch"));
(基本上没有变种的枚举,不能没有不安全的构造)作为一种解决方法。
要使用不稳定的功能,您需要使用夜间工具链并激活所需的不稳定功能。
Playground link
也可以看看:
#![feature(never_type)]
fn test_diverging(f: &Fn() -> !) {}