我有一個PRNG,我想允許閉包通過可變引用訪問。一切的壽命理論上可以工作了,這裏是什麼樣子:如何捕獲包含在迭代器中的可移動閉包從閉包中返回
fn someFunction<F, I>(mut crossover_point_iter_generator: F)
where F: FnMut(usize) -> I, I: Iterator<Item=usize>;
let mut rng = Isaac64Rng::from_seed(&[1, 2, 3, 4]);
someFunction(|x| (0..3).map(move |_| rng.gen::<usize>() % x));
這裏,關閉是創建一個包裝PRNG生成的值迭代器。這個迭代器包含一個閉包的映射,其中包含的包裝範圍爲x
,但問題在於它無意中也克隆了rng
,這也是我已驗證的。必須將其作爲移動關閉,因爲必須獲取x
的值,否則關閉將超過x
。
我試圖加入這一行強制其參考移動到閉合:
let rng = &mut rng;
然而,鏽抱怨此錯誤:
error: cannot move out of captured outer variable in an `FnMut` closure
能否性情不定地從訪問PRNG在移動閉包內部,如果不是,由於PRNG顯然超過了函數調用,是否有替代解決方案(除了重新設計API)?
編輯:
我已經重寫它來刪除複製問題和呼叫看起來是這樣的:
someFunction(|x| rng.gen_iter::<usize>().map(move |y| y % x).take(3));
這將導致一個新的錯誤:
error: cannot infer an appropriate lifetime for autoref due to conflicting requirements
附帶的,但[**不使用**模取得範圍內的隨機數](http://stackoverflow.com/questions/10984974/why-do-people-say-there-is-modulo-偏置時 - 使用 - 一個隨機數發生器)!對於這種情況,「rand」箱子具有「在一定範圍內隨機」功能。 – Shepmaster
@Shepmaster啊,謝謝。我對偏見問題很熟悉,但我沒有意識到Rng公開了一個界面來輕鬆處理這個問題!最好查看我正在使用的特徵的所有功能。我將假定它是[rand :: Rng :: gen_range()](https://doc.rust-lang.org/num/rand/trait.Rng.html#method.gen_range)? – vadix
是的,我懶得找到^ _ ^的功能。還有[長版本](https://doc.rust-lang.org/num/rand/distributions/range/struct.Range.html),但是'gen_range'更容易理解。 – Shepmaster