diff --git a/vlib/v/checker/for.v b/vlib/v/checker/for.v index 7bc025d6d9f6cd..ba50778480aeb3 100644 --- a/vlib/v/checker/for.v +++ b/vlib/v/checker/for.v @@ -195,12 +195,15 @@ fn (mut c Checker) for_in_stmt(mut node ast.ForInStmt) { c.error('map literal is immutable, it cannot be changed', node.cond.pos) } ast.SelectorExpr { - root_ident := node.cond.root_ident() or { node.cond.expr as ast.Ident } - if root_ident.kind != .unresolved { - if !(root_ident.obj as ast.Var).is_mut { - sym2 := c.table.sym(root_ident.obj.typ) - c.error('field `${sym2.name}.${node.cond.field_name}` is immutable, it cannot be changed', - node.cond.pos) + if root_ident := node.cond.root_ident() { + if root_ident.kind != .unresolved { + if var := node.scope.find_var(root_ident.name) { + if !var.is_mut { + sym2 := c.table.sym(root_ident.obj.typ) + c.error('field `${sym2.name}.${node.cond.field_name}` is immutable, it cannot be changed', + node.cond.pos) + } + } } } } diff --git a/vlib/v/tests/for_in_mut_mutable_app_field_test.v b/vlib/v/tests/for_in_mut_mutable_app_field_test.v new file mode 100644 index 00000000000000..0c8800e821f9f5 --- /dev/null +++ b/vlib/v/tests/for_in_mut_mutable_app_field_test.v @@ -0,0 +1,20 @@ +struct Item { +mut: + field []int +} + +struct App { +mut: + index [][]Item +} + +fn test_for_in_struct_with_mutable_array_field_indexed_several_times_in_the_loop_condition_part() { + mut app, x, y := App{[[Item{ + field: [1, 2, 3] + }]]}, 0, 0 + for i, mut v in app.index[x][y].field { + assert v != 0 + v = 555 + } + assert app.index[x][y] == Item{[555, 555, 555]} +}