函数类型vs闭包类型

编程入门 行业动态 更新时间:2024-10-23 23:27:13
本文介绍了函数类型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.

问题:

  • 这里实际不匹配是什么?该错误消息似乎暗示了 Fn vs闭包类型,但随后还有预期的外部fn,在错误消息中找到了fn
  • 如何使类型匹配?(即,将闭包转换为 fn 类型,因为它是纯净的)
  • 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
  • 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闭包类型

    本文发布于:2023-10-16 11:56:09,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1497488.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:类型   函数

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!