一連のボックス化された値に対してイテレータを使用しています。私はこのイテレータを、ボックス化された値への変更可能な参照の上にマップしたいと思います。ルックの反復参照可能な値にボックス化された値をマップする
以下の簡略化された例は、不変参照に対してこれをどのように達成できるかを示しています。この例はうまくコンパイルされます。
let indices = [0usize, 1usize, 2usize];
let vec = vec![Box::new(1.0), Box::new(2.0), Box::new(3.0)];
let i = indices.iter().map(|index| vec[*index].deref()).map(|x| *x + 1.0);
ただし、以下の例のように変更可能な参照の場合、コンパイラはエラーを生成します。
let indices = [0usize, 1usize, 2usize];
let mut vec = vec![Box::new(1.0), Box::new(2.0), Box::new(3.0)];
let i = indices.iter().map(|index| vec[*index].deref_mut()).map(|x| *x = *x + 1.0);
コンパイルエラーは以下の通りです:
これを固定することができる方法error[E0495]: cannot infer an appropriate lifetime for lifetime parameter in function call due to conflicting requirements
--> src\port_graph/mod.rs:200:40
|
200 | let i = indices.iter().map(|index| vec[*index].deref_mut()).map(|x| *x = *x + 1.0);
| ^^^^^^^^^^^
|
note: first, the lifetime cannot outlive the lifetime as defined on the body at 200:39...
--> src\port_graph/mod.rs:200:40
|
200 | let i = indices.iter().map(|index| vec[*index].deref_mut()).map(|x| *x = *x + 1.0);
| ^^^^^^^^^^^^^^^^^^^^^^^
note: ...so that closure can access `vec`
--> src\port_graph/mod.rs:200:40
|
200 | let i = indices.iter().map(|index| vec[*index].deref_mut()).map(|x| *x = *x + 1.0);
| ^^^
note: but, the lifetime must be valid for the scope of call-site for function at 200:39...
--> src\port_graph/mod.rs:200:40
|
200 | let i = indices.iter().map(|index| vec[*index].deref_mut()).map(|x| *x = *x + 1.0);
| ^^^^^^^^^^^^^^^^^^^^^^^
note: ...so that return value is valid for the call
--> src\port_graph/mod.rs:200:32
|
200 | let i = indices.iter().map(|index| vec[*index].deref_mut()).map(|x| *x = *x + 1.0);
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
?
編集:単純なベクトルの場合、単純に以下を実行できます。しかし、上記の例は、グラフの中のノードの部分集合(petgraph crate)を繰り返したい場合の単純化です。グラフ自体を消費したくありません。
let mut vec = vec![Box::new(1.0), Box::new(2.0), Box::new(3.0)];
let i = vec.iter_mut().map(|boxed| boxed.deref_mut()).map(|x| *x = *x + 1.0);