#E0057: 无效的赋值
= 的左边不能被赋值:常量、静态变量、没有用 let 声明的变量,或者闭包没有用 [ref name] 捕获的值。对 let 变量、它的字段或它的元素赋值。左边是一个值(例如调用结果)时是 E0140。在副本上设置字段而之后没有任何地方读取它(按值的 self 或参数、闭包的实参、for 绑定、xs[i] 的 let),修改就会丢失,这也是错误:接受 ref self 或 ref 参数,从闭包返回实参并使用结果,写 for ref x in xs,或者把元素写回去。
nabi
let count = 0;
coutn = count + 1;
error[E0057]: `coutn` is not declared; a variable is created only by `let` --> main.nabi:2:1 | 2 | coutn = count + 1; | ^^^^^ | = help: did you mean `count`? To declare a new variable, write `let coutn = count + 1;`
对你声明的变量赋值,或者用 let 声明一个新变量:
nabi
let count = 0;
count = count + 1;
println(f"{count}");
1
Nabi 没有通过赋值进行的声明:变量只能由 let 创建(5.1)。解构赋值中的每个名称也是如此,例如 (a, b) = (b, a);:先用 let 声明它们,或者用 let (a, b) = ..; 一次声明。
在副本上设置字段而之后没有任何地方读取它,也是这个错误:修改会丢失。结构体是值,所以按值的 self 或参数、闭包的实参(m.with(|a| { a.n += 1; }))、for 绑定和元素的 let(let q = xs[i];)持有的都是副本(2.3.8)。
nabi
struct Point { x: i32; y: i32; }
let ps = [Point { x: 1, y: 0 }, Point { x: 2, y: 0 }];
for p in ps { p.x = 7; }
error[E0057]: `p.x` is set on a copy of the element, so `ps` does not change --> main.nabi:4:15 | 4 | for p in ps { p.x = 7; } | ^^^ | = help: bind each element as a place with `for ref`: `for ref p in ps { p.x = 7; }`
for ref 把每个元素绑定为位置,所以写入会作用到列表上(3.13.3)。在方法中,接受 ref self;对于参数,接受 ref p;在闭包中,返回实参并使用结果;对于元素的 let,把它写回去(xs[i] = q;)。
nabi
struct Point { x: i32; y: i32; }
let ps = [Point { x: 1, y: 0 }, Point { x: 2, y: 0 }];
for ref p in ps { p.x = 7; }
println(f"{ps[0].x} {ps[1].x}");
7 7
相关错误码:E0027 找不到值或函数,E0038 变量与嵌套函数同名,E0140 对不是位置的值赋值
发现错误? 在 GitHub 上编辑此页 最后更新: