甲FnMut闭合无法克隆,出于显而易见的原因,但Fn封闭件具有一个不可变的范围; 有没有办法创建一个Fn闭包的"重复" ?
尝试克隆它会导致:
error[E0599]: no method named `clone` found for type `std::boxed::Box<std::ops::Fn(i8, i8) -> i8 + std::marker::Send + 'static>` in the current scope
--> src/main.rs:22:25
|
22 | fp: self.fp.clone(),
| ^^^^^
|
= note: self.fp is a function, perhaps you wish to call it
= note: the method `clone` exists but the following trait bounds were not satisfied:
`std::boxed::Box<std::ops::Fn(i8, i8) -> i8 + std::marker::Send> : std::clone::Clone`
Run Code Online (Sandbox Code Playgroud)
以某种方式将原始指针传递给Fn周围是安全的,例如:
let func_pnt = …Run Code Online (Sandbox Code Playgroud) 我目前正在尝试在Rust中实现一个简单的Parser-Combinator库.为此,我希望有一个泛型map函数来转换解析器的结果.
问题是我不知道如何复制持有闭包的结构.示例是Map以下示例中的结构.它有一个mapFunction存储函数的字段,它接收前一个解析器的结果并返回一个新结果.Map它本身就是一个可以与其他解析器进一步组合的解析器.
但是,对于要组合的解析器,我需要它们是可复制的(具有Clone特征限制),但是我该如何提供Map呢?
示例:(只有伪代码,很可能无法编译)
trait Parser<A> { // Cannot have the ": Clone" bound because of `Map`.
// Every parser needs to have a `run` function that takes the input as argument
// and optionally produces a result and the remaining input.
fn run(&self, input: ~str) -> Option<(A, ~str)>
}
struct Char {
chr: char
}
impl Parser<char> for Char {
// The char parser returns Some(char) if …Run Code Online (Sandbox Code Playgroud) 我有一个看起来像这样的结构:
pub struct MyStruct<F>
where
F: Fn(usize) -> f64,
{
field: usize,
mapper: F,
// fields omitted
}
Run Code Online (Sandbox Code Playgroud)
我如何实现Clone这个结构?
我发现复制函数体的一种方法是:
let mapper = |x| (mystruct.mapper)(x);
Run Code Online (Sandbox Code Playgroud)
但这会导致mapper与mystruct.mapper.
我正在使用这个问题的答案的策略,我有兴趣生成另一个序列,它是由迭代器映射创建的两个函数:
extern crate itertools_num;
use itertools_num::linspace;
fn main() {
// 440Hz as wave frequency (middle A)
let freq: f64 = 440.0;
// Time vector sampled at 880 times/s (~Nyquist), over 1s
let delta: f64 = 1.0 / freq / 2.0;
let time_1s = linspace(0.0, 1.0, (freq / 2.0) as usize)
.map(|sample| { sample * delta});
let (sine_440,
sine_100,
summed_signal): (Vec<f64>, Vec<f64>, Vec<f64>) =
time_1s.map(|time_sample| {
let sample_440 = (freq * &time_sample).sin();
let sample_100 = (100.0 * &time_sample).sin();
let …Run Code Online (Sandbox Code Playgroud)