From b3b86ea6d72c2abf91143ffb3563e954c657c336 Mon Sep 17 00:00:00 2001 From: yuyi Date: Wed, 20 May 2020 00:33:24 +0800 Subject: [PATCH] cgen: fix array_init has len but no init error --- vlib/v/gen/cgen.v | 6 ++++-- vlib/v/tests/array_init_test.v | 11 +++++++++++ 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/vlib/v/gen/cgen.v b/vlib/v/gen/cgen.v index 0397e6f7b1..2d397b8536 100644 --- a/vlib/v/gen/cgen.v +++ b/vlib/v/gen/cgen.v @@ -990,11 +990,13 @@ fn (mut g Gen) gen_assign_stmt(assign_stmt ast.AssignStmt) { ast.ArrayInit { is_fixed_array_init = it.is_fixed has_val = it.has_val + elem_type_str := g.typ(it.elem_type) if it.has_default { - elem_type_str := g.typ(it.elem_type) g.write('$elem_type_str _val_$it.pos.pos = ') g.expr(it.default_expr) g.writeln(';') + } else if it.has_len && it.elem_type == table.string_type { + g.writeln('$elem_type_str _val_$it.pos.pos = tos_lit("");') } } else {} @@ -3928,7 +3930,7 @@ fn (mut g Gen) array_init(it ast.ArrayInit) { g.write('0, ') } g.write('sizeof($elem_type_str), ') - if it.has_default { + if it.has_default || (it.has_len && it.elem_type == table.string_type) { g.write('&_val_$it.pos.pos)') } else { g.write('0)') diff --git a/vlib/v/tests/array_init_test.v b/vlib/v/tests/array_init_test.v index 0847f5bdad..99afc3f47b 100644 --- a/vlib/v/tests/array_init_test.v +++ b/vlib/v/tests/array_init_test.v @@ -28,3 +28,14 @@ fn test_array_init_with_default() { b2 := []string{len: 2, init: '111'} assert '$b2' == "['111', '111']" } + +fn test_array_init_with_len_no_default() { + a1 := []int{len: 4} + assert '$a1' == '[0, 0, 0, 0]' + + a2 := []string{len: 4} + assert '$a2' == "['', '', '', '']" + + a3 := []bool{len: 3} + assert '$a3' == '[false, false, false]' +}