[英]error to implement trait for function type in Rust
I want to implement the From
trait for an enum.我想为枚举实现
From
特征。 It's OK for usize
, but fail for function type. usize
,但 function 类型失败。
Is there any difference between usize and function type? usize 和 function 类型有什么区别吗?
The code:编码:
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
}
The error:错误:
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`.
The error says that From<fn(usize) -> usize {testf}>
is needed but only has From<fn(usize) -> usize>
.该错误表明
From<fn(usize) -> usize {testf}>
是必需的,但只有From<fn(usize) -> usize>
。 I think the problem is {testf}
, but I do not know why.我认为问题是
{testf}
,但我不知道为什么。
Thanks in advance提前致谢
In Rust, function definitions does not have the fn
type.在 Rust、function 定义中没有
fn
类型。 They have a distinct, unnameable type that the compiler spells out as signature {name}
, eg fn(usize) -> usize {testf}
.它们有一个独特的、不可命名的类型,编译器将其拼写为
signature {name}
,例如fn(usize) -> usize {testf}
。
This type can be coerced , ie converted, to the corresponding fn
type ( fn(usize) -> usize
), and usually it does so automatically, but when working with generics it does not.这种类型可以被强制转换,即转换为相应的
fn
类型( fn(usize) -> usize
),通常它会自动执行此操作,但在使用 generics 时不会。
You can force the compiler to coerce with as
:您可以强制编译器强制使用
as
:
fn testf(n: usize) -> usize { n * n }
let vf: Value = (testf as fn(usize) -> usize).into();
Or by specifying the type explicitly:或者通过明确指定类型:
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.