我想创建一个函数向量
let all_rerankers = vec![ match_full
, match_partial
, match_regex
, match_camel_case
];
但是,match_camel_case
需要比其他函数多一个参数,所以我可以为match_camel_case
定义一个闭包
// 3 is the extra parameter needed by match_camel_case
let close_camel_case = |str: &str, keyword: &str| {
match_camel_case(str, keyword, 3)
};
然后指定我的矢量类型:
let all_rerankers: Vec<|str: &str, kwd: &str| -> MatchScore>
= vec![ match_full
, match_partial
, match_regex
, close_camel_case
];
然而,编译它会向我显示Rust对待它们的方式不同:
mismatched types: expected `fn(&str, &str) -> MatchScore`,
found `|&str, &str| -> MatchScore`
(expected extern fn, found fn)
close_camel_case
^~~~~~~~~~~~~~~~
(我的vec!
宏中的类似错误)
它似乎也区分Fn
类型和闭包类型。我可以通过在闭包中包装每个match_*
函数来进行编译,但我确信有更好的解决方案。
问题:
Fn
vs封闭类型,但是错误消息中还有expected extern fn, found fn
fn
类型,因为它是纯粹的)我的rustc版本:rustc 0.12.0-pre-nightly (09cebc25a 2014-09-07 00:31:28 +0000)
(如果需要可以升级)
答案 0 :(得分:1)
这看起来像类型推断中的一些不幸的问题。如果你这样做:
let mut all_rerankers: Vec<|str: &str, kwd: &str| -> MatchScore> = Vec::new();
all_rerankers.push(match_full);
all_rerankers.push(match_partial);
all_rerankers.push(match_regex);
all_rerankers.push(close_camel_case);
然后一切都很好。复制很广泛,但您可以轻松编写一个调用可能如下所示的宏:
push_to!(all_rerankers;
match_full,
match_partial,
match_regex,
close_camel_case
)
这可能值得在Rust bug tracker中创建一个问题,但旧的关闭很快就会被弃用,所以我不确定这是否值得修复。