如何编写一个未实现的函数来返回没有虚拟代码的impl Trait?

时间:2018-04-01 16:48:41

标签: rust

我试过了:

trait T {}

fn f() -> impl T {
    unimplemented!();
}

fn main() {
    f();
}

但它给出了这个错误:

error[E0277]: the trait bound `!: T` is not satisfied
 --> src/main.rs:3:11
  |
3 | fn f() -> impl T {
  |           ^^^^^^ the trait `T` is not implemented for `!`
  |
  = note: the return type of a function must have a statically known size

如果f中的分支返回某些内容,则编译:

struct S {}

trait T {}

impl T for S {}

fn f(a: u32) -> impl T {
    if a == 0 {
        panic!();
    } else {
        S {}
    }
}

fn main() {
    f(5);
}

1 个答案:

答案 0 :(得分:2)

这是known issue

简单(作弊)的答案是实现impl T for ! {} 的特征:

trait T {
    fn hello(&self) -> u32;
}

impl T for ! {
    fn hello(&self) -> u32 {
        *self
    }
}

您可以在tracking issue for promoting ! to a type中看到,围绕哪种特征为类型实现了很多讨论。

还有an RFC to implement traits automatically for !,但未被接受。这需要"实施"特征中的任何方法因为another proposed RFC也被推迟了:

{{1}}