[英]Simplify function declaration
I would like to simplify the declaration of the following function:我想简化以下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))
}
I tried to replace the Fn
trait by F
in the return value, but it raises an error:我试图在返回值中用
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
How can simplify this declaration to avoid duplication of Fn(i32, i32) -> i32 + 'a
?如何简化此声明以避免重复
Fn(i32, i32) -> i32 + 'a
?
You could use this technique .你可以使用这种技术。 In short, define a new trait that requires
Fn(i32, i32) -> i32
and implement it for any type that already implements Fn(i32, i32) -> i32
:简而言之,定义一个需要
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))
}
Note, however, that this might be less readable than just repeating Fn(i32, i32) -> i32
in the signature of oper
.但是请注意,这可能比在
oper
的签名中重复Fn(i32, i32) -> i32
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.