diff --git a/vlib/v/checker/for.v b/vlib/v/checker/for.v index 94bbea266a..e27126935e 100644 --- a/vlib/v/checker/for.v +++ b/vlib/v/checker/for.v @@ -95,6 +95,9 @@ fn (mut c Checker) for_in_stmt(mut node ast.ForInStmt) { node.scope.update_var_type(node.key_var, key_type) } mut value_type := c.table.value_type(typ) + if sym.kind == .string { + value_type = ast.byte_type + } if value_type == ast.void_type || typ.has_flag(.optional) { if typ != ast.void_type { c.error('for in: cannot index `${c.table.type_to_str(typ)}`', node.cond.pos()) diff --git a/vlib/v/gen/c/for.v b/vlib/v/gen/c/for.v index 4d399bacd7..a7e8b35b46 100644 --- a/vlib/v/gen/c/for.v +++ b/vlib/v/gen/c/for.v @@ -299,14 +299,15 @@ fn (mut g Gen) for_in_stmt(node ast.ForInStmt) { } else { node.cond } + field_accessor := if node.cond_type.is_ptr() { '->' } else { '.' } i := if node.key_var in ['', '_'] { g.new_tmp_var() } else { node.key_var } g.write('for (int $i = 0; $i < ') g.expr(cond) - g.writeln('.len; ++$i) {') + g.writeln('${field_accessor}len; ++$i) {') if node.val_var != '_' { - g.write('\tbyte ${c_name(node.val_var)} = ') + g.write('\tu8 ${c_name(node.val_var)} = ') g.expr(cond) - g.writeln('.str[$i];') + g.writeln('${field_accessor}str[$i];') } } else if node.kind == .struct_ { cond_type_sym := g.table.sym(node.cond_type) diff --git a/vlib/v/tests/inout/printing_for_v_in_a.out b/vlib/v/tests/inout/printing_for_v_in_a.out new file mode 100644 index 0000000000..4f19f936f5 --- /dev/null +++ b/vlib/v/tests/inout/printing_for_v_in_a.out @@ -0,0 +1,11 @@ +97 +98 +99 +abc +23 +77 +abc +> k: abc | v: xyz +> k: def | v: jkl +abc +abc diff --git a/vlib/v/tests/inout/printing_for_v_in_a.vv b/vlib/v/tests/inout/printing_for_v_in_a.vv new file mode 100644 index 0000000000..5b1486f991 --- /dev/null +++ b/vlib/v/tests/inout/printing_for_v_in_a.vv @@ -0,0 +1,30 @@ +interface Any {} + +fn abc(a Any) { + if a is string { + for x in a { + println(x) + } + } + if a is []u8 { + for x in a { + println(x) + } + } + if a is map[string]string { + for k, v in a { + println('> k: $k | v: $v') + } + } + println(@FN) +} + +fn main() { + abc('abc') + abc([u8(23), 77]) + abc({ + 'abc': 'xyz' + 'def': 'jkl' + }) + abc(123) +}