From f715d49156e872ba63d5840f334a4d54f4b60c30 Mon Sep 17 00:00:00 2001 From: yuyi Date: Thu, 24 Oct 2024 22:14:35 +0800 Subject: [PATCH] cgen: fix struct field init with fixed array using index (fix #22616) (#22641) --- vlib/v/gen/c/struct.v | 3 ++- ...uct_field_init_with_fixed_array_init_test.v | 18 ++++++++++++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) create mode 100644 vlib/v/tests/structs/struct_field_init_with_fixed_array_init_test.v diff --git a/vlib/v/gen/c/struct.v b/vlib/v/gen/c/struct.v index 413664627ff1ea..f662fe37969c3a 100644 --- a/vlib/v/gen/c/struct.v +++ b/vlib/v/gen/c/struct.v @@ -673,7 +673,8 @@ fn (mut g Gen) struct_init_field(sfield ast.StructInitField, language ast.Langua info := field_unwrap_sym.info as ast.ArrayFixed g.fixed_array_var_init(g.expr_string(sfield.expr), sfield.expr.is_auto_deref_var(), info.elem_type, info.size) - } else if field_unwrap_sym.kind == .array_fixed && sfield.expr is ast.CallExpr { + } else if field_unwrap_sym.kind == .array_fixed && (sfield.expr is ast.CallExpr + || (sfield.expr is ast.ArrayInit && sfield.expr.has_index)) { info := field_unwrap_sym.info as ast.ArrayFixed tmp_var := g.expr_with_var(sfield.expr, sfield.typ, sfield.expected_type) g.fixed_array_var_init(tmp_var, false, info.elem_type, info.size) diff --git a/vlib/v/tests/structs/struct_field_init_with_fixed_array_init_test.v b/vlib/v/tests/structs/struct_field_init_with_fixed_array_init_test.v new file mode 100644 index 00000000000000..61c8551e625ea3 --- /dev/null +++ b/vlib/v/tests/structs/struct_field_init_with_fixed_array_init_test.v @@ -0,0 +1,18 @@ +fn test_struct_field_init_with_fixed_array_init() { + mut a := [5]int{init: [1, 2][index] or { 0 }} + struct ArrayTest { + aa [5]int + } + + array_a := ArrayTest{ + aa: a + } + println('array_a: ${array_a}') + assert array_a.aa == [1, 2, 0, 0, 0]! + + array_b := ArrayTest{ + aa: [5]int{init: [1, 2][index] or { 0 }} + } + println('array_b: ${array_b}') + assert array_b.aa == [1, 2, 0, 0, 0]! +}