closures - 函数类型与闭包类型

标签 closures rust

我想创建一个函数向量

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_* 函数包装在一个闭包中来进行编译,但我确信有更好的解决方案。

问题:

  1. 这里实际的不匹配是什么?错误消息似乎提示 Fn vs 闭包类型,但是错误消息中还有 expected extern fn, found fn
  2. 如何使类型匹配? (即,将闭包转换为 fn 类型,因为它是纯的)

我的 rustc 版本:rustc 0.12.0-pre-nightly (09cebc25a 2014-09-07 00:31:28 +0000)(如果需要可以升级)

最佳答案

这看起来像是类型推断中的一些不幸问题。如果你这样做:

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 中创建一个问题,但是旧的闭包很快就会被弃用,所以我不确定这是否值得修复。

关于closures - 函数类型与闭包类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25887793/

相关文章:

rust - Rust可以存储对 parent 的引用吗?

rust - 尝试将盒装 dyn 特性传递给函数时出现 "borrowed value does not live long enough"错误

rust - 如何实现原子 32 位整数类型 AtomicU32?

compiler-errors - 闭包——移动值的使用

Javascript 事件处理程序 `this` 闭包内的绑定(bind)不起作用

swift - UIView,CMDeviceMotionHandler : unowned may only be applied to class and class-bound protocol types

rust - 宏匹配 token 递归扩展

struct - 在 Rust 中调用存储在结构中的堆栈分配闭包

swift - 为什么这不算作闭包捕获?

error-handling - Rust为调试和 Release模式设置了不同的紧急输出