函数类型vs闭包类型 [英] Function type vs Closure type

查看:39
本文介绍了函数类型vs闭包类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个函数向量

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.

问题:

  1. 这里实际不匹配是什么?该错误消息似乎暗示了 Fn vs闭包类型,但随后还有预期的外部fn,在错误消息中找到了fn
  2. 如何使类型匹配?(即,将闭包转换为 fn 类型,因为它是纯净的)
  1. What is the actual mismatch here? the error message seems to suggest Fn vs closure type, but then there's also expected extern fn, found fn in the error message
  2. How can I make the type match? (namely, convert closure into fn type, since it's pure)

我的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闭包类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆