【发布时间】:2019-12-14 08:24:59
【问题描述】:
我有一个函数创建一个FnMut 闭包,move-捕获其中一个参数。我收到编译器错误,因为参数不是mut。我不明白问题是什么,因为我 move 它并且闭包并没有真正使用参数本身。
代码:
pub struct Position {
pub x: usize,
pub y: usize,
}
fn map_it(p: Position) -> impl FnMut(usize) -> usize {
move |param| {
p.x += 1;
p.x + p.y + param
}
}
错误:
error[E0594]: cannot assign to `p.x`, as `p` is not declared as mutable
--> src/lib.rs:8:9
|
6 | fn map_it(p: Position) -> impl FnMut(usize) -> usize {
| - help: consider changing this to be mutable: `mut p`
7 | move |param| {
8 | p.x += 1;
| ^^^^^^^^ cannot assign
【问题讨论】:
-
为什么你认为你应该能够改变一个没有标记为
mut的变量?
标签: rust closures immutability