带有未装箱关闭的错误消息 [英] Error message with unboxed closures
问题描述
这个使用未装箱闭包的小型 FizzBuzz 程序给出了一个相当神秘的错误信息.
This small FizzBuzz program using unboxed closures gives a rather mysterious error message.
fn fizzbuzz<F: Fn(i64) -> bool>(n: i64, f: F, fs: &str, b: F, bs: &str) {
for i in range(1i64, n+1) {
match (f(i), b(i)) {
(true, true) => println!("{:3}: {}{}", i, fs, bs),
(true, _) => println!("{:3}: {}", i, fs),
(_, true) => println!("{:3}: {}", i, bs),
_ => (),
}
}
}
fn main() {
fizzbuzz(30,
|&: i: i64| { i % 3 == 0 }, "fizz",
|&: j: i64| { j % 5 == 0 }, "buzz");
}
错误信息:
<anon>:15:14: 15:40 error: mismatched types: expected `closure[<anon>:14:14: 14:40]`, found `closure[<anon>:15:14: 15:40]` (expected closure, found a different closure)
<anon>:15 |&: j: i64| { j % 5 == 0 }, "buzz");
^~~~~~~~~~~~~~~~~~~~~~~~~~
error: aborting due to previous error
有人可以描述一下错误吗?谢谢.
Could someone describe the error please? Thanks.
推荐答案
这段代码说明了问题的本质:
This piece of code demonstrates the essence of the problem:
fn show_both<S: Show>(x: S, y: S) {
println!("{} {}", x, y);
}
您只能使用相同类型的两个参数来调用它,即这是允许的:
You can only call it with both arguments of the same type, i.e. this is allowed:
let x: i32 = 10;
let y: i32 = 20;
show_both(x, y);
但这不是:
let x: i32 = 10;
let y: f64 = 20.0;
show_both(x, y);
这是相当自然的:您指定两个参数必须是同一类型,即使该类型可以是任意的,只要它实现了Show
.
This is fairly natural: you specified that both of the parameters must be of the same type, even though this type can be arbitrary as long as it implements Show
.
您的代码中具有基本相同的内容:
You have essentially the same thing in your code:
fn fizzbuzz<F: Fn(i64) -> bool>(n: i64, f: F, fs: &str, b: F, bs: &str)
您声明 f
和 b
必须具有相同的类型.然而,对于每个未装箱的闭包,编译器会生成不同的类型——这也很自然,因为不同的闭包可以捕获不同的变量.
You declared that both f
and b
must have the same type. However, for each unboxed closure the compiler generates a different type - this is quite natural as well, given that different closures can capture different variables.
你需要指定不同的类型参数才能传递不同的闭包:
You need to specify different type parameters in order to be able to pass different closures:
fn fizzbuzz<F1, F2>(n: i64, f: F1, fs: &str, b: F2, bs: &str)
where F1: Fn(i64) -> bool,
F2: Fn(i64) -> bool
这篇关于带有未装箱关闭的错误消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!