From 9abb53aa1ed067766c1df4e7db6eda3947105990 Mon Sep 17 00:00:00 2001 From: yuyi Date: Wed, 18 Dec 2024 20:52:24 +0800 Subject: [PATCH] fix other cases and add tests --- vlib/v/gen/c/struct.v | 23 +++++++++++++++---- ...uct_field_init_with_fixed_array_opt_test.v | 23 ++++++++++++++++--- 2 files changed, 38 insertions(+), 8 deletions(-) diff --git a/vlib/v/gen/c/struct.v b/vlib/v/gen/c/struct.v index f17ab3f37afe6d..86b905b83bc334 100644 --- a/vlib/v/gen/c/struct.v +++ b/vlib/v/gen/c/struct.v @@ -688,13 +688,26 @@ fn (mut g Gen) struct_init_field(sfield ast.StructInitField, language ast.Langua if field_unwrap_sym.info is ast.ArrayFixed { match sfield.expr { ast.Ident, ast.SelectorExpr { - g.fixed_array_var_init(g.expr_string(sfield.expr), is_auto_deref_var, - field_unwrap_sym.info.elem_type, field_unwrap_sym.info.size) + if sfield.expected_type.has_flag(.option) { + if field_unwrap_typ.has_flag(.option) { + g.expr_with_opt(sfield.expr, sfield.expected_type, field_unwrap_typ) + } else { + g.expr_with_fixed_array_opt(sfield.expr, sfield.expected_type, + field_unwrap_typ) + } + } else { + g.fixed_array_var_init(g.expr_string(sfield.expr), is_auto_deref_var, + field_unwrap_sym.info.elem_type, field_unwrap_sym.info.size) + } } ast.CastExpr, ast.CallExpr { - if sfield.expected_type.has_flag(.option) && !field_unwrap_typ.has_flag(.option) { - g.expr_with_fixed_array_opt(sfield.expr, sfield.expected_type, - field_unwrap_typ) + if sfield.expected_type.has_flag(.option) { + if field_unwrap_typ.has_flag(.option) { + g.expr_with_opt(sfield.expr, sfield.expected_type, field_unwrap_typ) + } else { + g.expr_with_fixed_array_opt(sfield.expr, sfield.expected_type, + field_unwrap_typ) + } } else { tmp_var := g.expr_with_var(sfield.expr, sfield.expected_type, false) diff --git a/vlib/v/tests/structs/struct_field_init_with_fixed_array_opt_test.v b/vlib/v/tests/structs/struct_field_init_with_fixed_array_opt_test.v index 9c9fd75ed56e21..f07c2166da9efb 100644 --- a/vlib/v/tests/structs/struct_field_init_with_fixed_array_opt_test.v +++ b/vlib/v/tests/structs/struct_field_init_with_fixed_array_opt_test.v @@ -6,10 +6,27 @@ struct Foo { } fn test_struct_field_init_with_fixed_array_opt() { - f := Foo{ + f1 := Foo{ bar: 1 baz: Arr([u8(5), 4, 3, 2]!) } - println(f) - assert f.baz as Arr == [u8(5), 4, 3, 2]! + println(f1) + assert f1.baz as Arr == [u8(5), 4, 3, 2]! + + f2 := Foo{ + bar: 1 + baz: ?Arr(none) + } + println(f2) + assert f2.bar == 1 + assert f2.baz == none + + arr := Arr([u8(5), 4, 3, 2]!) + f3 := Foo{ + bar: 1 + baz: arr + } + println(f3) + assert f3.bar == 1 + assert f3.baz as Arr == [u8(5), 4, 3, 2]! }