繁体   English   中英

简化 function 声明

[英]Simplify function declaration

我想简化以下function的声明:

use regex::Regex;

fn oper<'a, F>(regex: &str, op: F) -> (Regex, Box<dyn Fn(i32, i32) -> i32 + 'a>)
where F: Fn(i32, i32) -> i32 + 'a
{
    (Regex::new(regex).unwrap(), Box::new(op))
}

我试图在返回值中用F替换Fn特征,但它引发了一个错误:

fn oper<'a, F>(regex: &str, op: F) -> (Regex, Box<dyn F>)
where F: Fn(i32, i32) -> i32 + 'a
{
    (Regex::new(regex).unwrap(), Box::new(op))
}
error[E0404]: expected trait, found type parameter `F`
  --> src/lib.rs:5:55
   |
5  |   fn oper<'a, F>(regex: &str, op: F) -> (Regex, Box<dyn F>)
   |                                                         ^ help: a trait with a similar name exists: `Fn`

error: aborting due to previous error

如何简化此声明以避免重复Fn(i32, i32) -> i32 + 'a

你可以使用这种技术 简而言之,定义一个需要Fn(i32, i32) -> i32的新特征,并为已经实现Fn(i32, i32) -> i32的任何类型实现它:

use regex::Regex;

// 1. Create a new trait
pub trait MyFn: Fn(i32, i32) -> i32 {}

// 2. Implement it
impl<T> MyFn for T where T: Fn(i32, i32) -> i32 {}

fn oper<'a, F>(regex: &str, op: F) -> (Regex, Box<dyn MyFn + 'a>)
    where F: MyFn + 'a
{
    (Regex::new(regex).unwrap(), Box::new(op))
}

但是请注意,这可能比在oper的签名中重复Fn(i32, i32) -> i32

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM