diff --git a/vlib/v/gen/c/assign.v b/vlib/v/gen/c/assign.v index 024812e142ce44..a8df4a0df24508 100644 --- a/vlib/v/gen/c/assign.v +++ b/vlib/v/gen/c/assign.v @@ -891,7 +891,13 @@ fn (mut g Gen) gen_cross_var_assign(node &ast.AssignStmt) { ast.Ident { left_typ := node.left_types[i] left_sym := g.table.sym(left_typ) - anon_ctx := if g.anon_fn { '${closure_ctx}->' } else { '' } + mut anon_ctx := '' + if g.anon_fn { + obj := left.scope.find(left.name) + if obj is ast.Var && obj.is_inherited { + anon_ctx = '${closure_ctx}->' + } + } if left_sym.kind == .function { g.write_fn_ptr_decl(left_sym.info as ast.FnType, '_var_${left.pos.pos}') g.writeln(' = ${anon_ctx}${c_name(left.name)};') diff --git a/vlib/v/tests/closure_test.v b/vlib/v/tests/closure_test.v index 303a4f7200ffd0..10613616545671 100644 --- a/vlib/v/tests/closure_test.v +++ b/vlib/v/tests/closure_test.v @@ -223,3 +223,23 @@ fn test_closure_over_variable_that_is_returned_from_a_multi_value_function() { a() println(two) } + +fn test_cross_var_assign_without_inherited() { + f := fn () { + mut left := 1 + mut right := 2 + left, right = right, left + assert left == 2 && right == 1 + } + f() +} + +fn test_cross_var_assign_with_inherited() { + mut left := 1 + mut right := 2 + f := fn [mut left, mut right] () { + left, right = right, left + assert left == 2 && right == 1 + } + f() +}