在 Rust 中实现函数类型特征的错误

error to implement trait for function type in Rust

我想为枚举实现 From 特性。 usize 没问题,但函数类型失败。

usize和function type有区别吗?

代码:

type Foo = fn (usize) -> usize;

enum Value {
    Number(usize),
    Function(Foo),
}

impl From<usize> for Value {
    fn from(n: usize) -> Self {
        Value::Number(n)
    }
}
impl From<Foo> for Value {
    fn from(f: Foo) -> Self {
        Value::Function(f)
    }
}

fn main() {
    let n: usize = 123;
    let vn: Value = n.into(); // OK for usize

    fn testf(n: usize) -> usize { n * n }
    let vf: Value = testf.into(); // fail for Foo
}

错误:

error[E0277]: the trait bound `Value: From<fn(usize) -> usize {testf}>` is not satisfied
  --> t.rs:24:27
   |
24 |     let vf: Value = testf.into(); // fail for Foo
   |                           ^^^^ the trait `From<fn(usize) -> usize {testf}>` is not implemented for `Value`
   |
   = help: the following implementations were found:
             <Value as From<fn(usize) -> usize>>
             <Value as From<usize>>
   = note: required because of the requirements on the impl of `Into<Value>` for `fn(usize) -> usize {testf}`

error: aborting due to previous error

For more information about this error, try `rustc --explain E0277`.

错误说需要 From<fn(usize) -> usize {testf}> 但只有 From<fn(usize) -> usize>。我认为问题是 {testf},但我不知道为什么。

提前致谢

在 Rust 中,函数定义没有 fn 类型。它们有一个独特的、不可命名的类型,编译器将其拼写为 signature {name},例如fn(usize) -> usize {testf}.

这种类型可以强制,即转换为相应的fn类型(fn(usize) -> usize),通常它会自动转换,但是当使用泛型它不会。

您可以强制编译器强制使用 as:

fn testf(n: usize) -> usize { n * n }
let vf: Value = (testf as fn(usize) -> usize).into();

或者通过明确指定类型:

fn testf(n: usize) -> usize { n * n }
let testf_fn: fn(usize) -> usize = testf;
let vf: Value = testf_fn.into();