mirror of
https://github.com/vlang/v.git
synced 2023-08-10 21:13:21 +03:00
checker, cgen: fix printing in 'for v in a' (#14146)
This commit is contained in:
parent
9355048b6c
commit
c819f0f86f
@ -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())
|
||||
|
@ -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)
|
||||
|
11
vlib/v/tests/inout/printing_for_v_in_a.out
Normal file
11
vlib/v/tests/inout/printing_for_v_in_a.out
Normal file
@ -0,0 +1,11 @@
|
||||
97
|
||||
98
|
||||
99
|
||||
abc
|
||||
23
|
||||
77
|
||||
abc
|
||||
> k: abc | v: xyz
|
||||
> k: def | v: jkl
|
||||
abc
|
||||
abc
|
30
vlib/v/tests/inout/printing_for_v_in_a.vv
Normal file
30
vlib/v/tests/inout/printing_for_v_in_a.vv
Normal file
@ -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)
|
||||
}
|
Loading…
Reference in New Issue
Block a user