From c624de8523141d14796a7bc0d80d042ae5a36944 Mon Sep 17 00:00:00 2001 From: yuyi Date: Tue, 17 May 2022 00:37:39 +0800 Subject: [PATCH] cgen: fix struct field array index error (#14417) --- vlib/v/gen/c/index.v | 3 +-- vlib/v/tests/struct_field_array_index_test.v | 17 +++++++++++++++++ 2 files changed, 18 insertions(+), 2 deletions(-) create mode 100644 vlib/v/tests/struct_field_array_index_test.v diff --git a/vlib/v/gen/c/index.v b/vlib/v/gen/c/index.v index d62d6e3cba..afdcccbcdd 100644 --- a/vlib/v/gen/c/index.v +++ b/vlib/v/gen/c/index.v @@ -172,8 +172,7 @@ fn (mut g Gen) index_of_array(node ast.IndexExpr, sym ast.TypeSymbol) { } // `vals[i].field = x` is an exception and requires `array_get`: // `(*(Val*)array_get(vals, i)).field = x;` - is_selector := node.left is ast.SelectorExpr - if g.is_assign_lhs && !is_selector && node.is_setter { + if g.is_assign_lhs && node.is_setter { is_direct_array_access := (g.fn_decl != 0 && g.fn_decl.is_direct_arr) || node.is_direct is_op_assign := g.assign_op != .assign && info.elem_type != ast.string_type if is_direct_array_access { diff --git a/vlib/v/tests/struct_field_array_index_test.v b/vlib/v/tests/struct_field_array_index_test.v new file mode 100644 index 0000000000..05b158fb88 --- /dev/null +++ b/vlib/v/tests/struct_field_array_index_test.v @@ -0,0 +1,17 @@ +struct App { +mut: + buffer []string +} + +fn test_struct_field_array_index() { + mut app := &App{ + buffer: []string{len: 2} + } + + app.buffer[0] += 'hello' + app.buffer[1] += 'world' + + println(app) + + assert app.buffer == ['hello', 'world'] +}