簡體   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