我有以下代码(游乐场):
// Two dummy functions, both with the signature `fn(u32) -> bool`
fn foo(x: u32) -> bool {
x % 2 == 0
}
fn bar(x: u32) -> bool {
x == 27
}
fn call_both<F>(a: F, b: F)
where
F: Fn(u32) -> bool,
{
a(5);
b(5);
}
fn main() {
call_both(foo, bar); // <-- error
}
Run Code Online (Sandbox Code Playgroud)
对我来说,它看起来这应该是编译foo
和bar
具有相同的签名:fn(u32) -> bool
.然而,我收到以下错误:
error[E0308]: mismatched types
--> src/main.rs:20:20
|
20 | call_both(foo, bar);
| ^^^ …
Run Code Online (Sandbox Code Playgroud) 我试图创建闭包矢量:
fn main() {
let mut vec = Vec::new();
vec.push(Box::new(|| 10));
vec.push(Box::new(|| 20));
println!("{}", vec[0]());
println!("{}", vec[1]());
}
Run Code Online (Sandbox Code Playgroud)
这产生了以下错误报告:
error[E0308]: mismatched types
--> src/main.rs:5:23
|
5 | vec.push(Box::new(|| 20));
| ^^^^^ expected closure, found a different closure
|
= note: expected type `[closure@src/main.rs:4:23: 4:28]`
found type `[closure@src/main.rs:5:23: 5:28]`
= note: no two closures, even if identical, have the same type
= help: consider boxing your closure and/or using it as a trait object
Run Code Online (Sandbox Code Playgroud)
我通过明确指定类型来修复它:
let mut vec: Vec<Box<Fn() -> i32>> …
Run Code Online (Sandbox Code Playgroud) 我有两个虚函数:
fn foo() -> u32 { 3 }
fn bar() -> u32 { 7 }
Run Code Online (Sandbox Code Playgroud)
我想创建一个盒装的函数指针切片:Box<[fn() -> u32]>
.我想用box
语法来做(我知道它不是两个元素所必需的,但我的实际用例是不同的).
我尝试了几件事(游乐场):
// Version A
let b = box [foo, bar] as Box<[_]>;
// Version B
let tmp = [foo, bar];
let b = box tmp as Box<[_]>;
// Version C
let b = Box::new([foo, bar]) as Box<[_]>;
Run Code Online (Sandbox Code Playgroud)
版本B和C工作正常(C虽然不会对我有用Box::new
),但版本A错误:
error[E0605]: non-primitive cast: `std::boxed::Box<[fn() -> u32; 2]>` as `std::boxed::Box<[fn() -> u32 {foo}]>`
--> src/main.rs:8:13
|
8 …
Run Code Online (Sandbox Code Playgroud) rust ×3