我想From為列舉實作特征。可以usize,但函式型別失敗。
usize 和函式型別之間有什么區別嗎?
代碼:
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},但我不知道為什么。
提前致謝
uj5u.com熱心網友回復:
在 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();
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/402012.html
下一篇:如何總結for回圈中的所有答案?
