[英]error to implement trait for function type in Rust
我想为枚举实现From
特征。 usize
,但 function 类型失败。
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
}
错误:
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、function 定义中没有fn
类型。 它们有一个独特的、不可命名的类型,编译器将其拼写为signature {name}
,例如fn(usize) -> usize {testf}
。
这种类型可以被强制转换,即转换为相应的fn
类型( fn(usize) -> usize
),通常它会自动执行此操作,但在使用 generics 时不会。
您可以强制编译器强制使用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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.