我想创建一个函数向量
let all_rerankers = vec![ match_full , match_partial , match_regex , match_camel_case ];但是, match_camel_case 比其他函数需要更多的参数,因此尽管我可以为 match_camel_case
However, match_camel_case needs one more parameter than other functions, so I though I could define a closure for 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) };,然后指定我的向量的类型:
and then specify the type of my vector:
let all_rerankers: Vec<|str: &str, kwd: &str| -> MatchScore> = vec![ match_full , match_partial , match_regex , close_camel_case ];但是编译它告诉我Rust对待它们的方式有所不同:
However compiling it shows me that Rust treats them differently:
mismatched types: expected `fn(&str, &str) -> MatchScore`, found `|&str, &str| -> MatchScore` (expected extern fn, found fn) close_camel_case ^~~~~~~~~~~~~~~~(以及我的 vec!宏中的类似类型错误)
(and similar type error in my vec! macro)
似乎也可以区分 Fn 类型和闭包类型.我可以通过将每个 match _ * 函数包装在一个闭包中来进行编译,但是我敢肯定有更好的解决方案.
It also seem to distinguish between Fn type and closure type. I can make this compile by wrapping every match_* function in a closure, but I'm sure there's a better solution.
问题:
我的rustc版本: rustc 0.12.0-pre-nightly(09cebc25a 2014-09-07 00:31:28 +0000)(可根据需要进行升级)
my rustc version: rustc 0.12.0-pre-nightly (09cebc25a 2014-09-07 00:31:28 +0000) (can upgrade if needed)
推荐答案这似乎是类型推断中的一些不幸问题.如果您这样做:
This looks like some unfortunate problem in type inference. If you do this:
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);然后一切都很好.复制是广泛的,但是您可以轻松编写一个其调用看起来像这样的宏:
Then everything is fine. The duplication is extensive, but you can easily write a macro whose invocation could look like this:
push_to!(all_rerankers; match_full, match_partial, match_regex, close_camel_case )这可能值得在 Rust bug tracker 中创建问题,但是旧的闭包将是很快就弃用了,所以我不确定是否值得解决.
This probably deserves creating an issue in Rust bug tracker, but old closures will be deprecated soon, so I'm not sure if this is worth fixing.
更多推荐
函数类型vs闭包类型
发布评论