diff --git a/vlib/v/gen/cgen.v b/vlib/v/gen/cgen.v index b96e9e5caf..59611b1411 100644 --- a/vlib/v/gen/cgen.v +++ b/vlib/v/gen/cgen.v @@ -1283,14 +1283,14 @@ fn (mut g Gen) for_in(it ast.ForInStmt) { g.writeln('// FOR IN array') styp := g.typ(it.val_type) val_sym := g.table.get_type_symbol(it.val_type) - cond_type_is_ptr := it.cond_type.is_ptr() tmp := g.new_tmp_var() - tmp_type := if cond_type_is_ptr { 'array *' } else { 'array' } - g.write('$tmp_type $tmp = ') + g.write(g.typ(it.cond_type)) + g.write(' $tmp = ') g.expr(it.cond) g.writeln(';') i := if it.key_var in ['', '_'] { g.new_tmp_var() } else { it.key_var } - op_field := if cond_type_is_ptr { '->' } else { '.' } + op_field := if it.cond_type.is_ptr() { '->' } else { '.' } + + if it.cond_type.share() == .shared_t { 'val.' } else { '' } g.writeln('for (int $i = 0; $i < $tmp${op_field}len; ++$i) {') if it.val_var != '_' { if val_sym.kind == .function { @@ -1350,9 +1350,9 @@ fn (mut g Gen) for_in(it ast.ForInStmt) { g.writeln('// FOR IN map') idx := g.new_tmp_var() atmp := g.new_tmp_var() - atmp_styp := g.typ(it.cond_type) - arw_or_pt := if it.cond_type.nr_muls() > 0 { '->' } else { '.' } - g.write('$atmp_styp $atmp = ') + arw_or_pt := if it.cond_type.is_ptr() { '->' } else { '.' } + g.write(g.typ(it.cond_type)) + g.write(' $atmp = ') g.expr(it.cond) g.writeln(';') g.writeln('for (int $idx = 0; $idx < $atmp${arw_or_pt}key_values.len; ++$idx) {') diff --git a/vlib/v/tests/array_test.v b/vlib/v/tests/array_test.v new file mode 100644 index 0000000000..5340fc46bf --- /dev/null +++ b/vlib/v/tests/array_test.v @@ -0,0 +1,20 @@ +fn test_for_in_array_named_array() { + mut array := [1] + for elem in array { + assert elem == 1 + } + for mut elem in array { + assert *elem == 1 + elem = 2 + assert *elem == 2 + } +} + +fn test_for_in_shared_array_named_array() { + shared array := &[1] + rlock array { + for elem in array { + assert elem == 1 + } + } +}