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

Bin*_* Wu 4 function traits rust

我想实现From枚举的特征。对于 可以usize,但对于函数类型则失败。

usize 和 function 类型有什么区别吗?

代码:

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
}
Run Code Online (Sandbox Code Playgroud)

错误:

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`.
Run Code Online (Sandbox Code Playgroud)

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

提前致谢

Cha*_*man 5

在 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();
Run Code Online (Sandbox Code Playgroud)

或者通过显式指定类型:

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