From ab7917ec0209f8ffb192d056182b08d15326e16d Mon Sep 17 00:00:00 2001 From: yuyi Date: Sat, 23 Sep 2023 15:50:54 +0800 Subject: [PATCH] cgen: fix struct field option type with default value init --- vlib/v/gen/c/struct.v | 3 +-- ...field_option_type_with_default_value_init_test.v | 13 +++++++++++++ 2 files changed, 14 insertions(+), 2 deletions(-) create mode 100644 vlib/v/tests/struct_field_option_type_with_default_value_init_test.v diff --git a/vlib/v/gen/c/struct.v b/vlib/v/gen/c/struct.v index 770d3cb03e1f0f..2b0297ca9b6291 100644 --- a/vlib/v/gen/c/struct.v +++ b/vlib/v/gen/c/struct.v @@ -359,8 +359,7 @@ fn (mut g Gen) zero_struct_field(field ast.StructField) bool { if field.has_default_expr { if sym.kind in [.sum_type, .interface_] { if field.typ.has_flag(.option) { - g.expr_opt_with_cast(field.default_expr, field.default_expr_typ.set_flag(.option), - field.typ) + g.expr_with_opt(field.default_expr, field.default_expr_typ, field.typ) } else { g.expr_with_cast(field.default_expr, field.default_expr_typ, field.typ) } diff --git a/vlib/v/tests/struct_field_option_type_with_default_value_init_test.v b/vlib/v/tests/struct_field_option_type_with_default_value_init_test.v new file mode 100644 index 00000000000000..d154b540c2f091 --- /dev/null +++ b/vlib/v/tests/struct_field_option_type_with_default_value_init_test.v @@ -0,0 +1,13 @@ +type SomeType = SomeStruct | string + +struct SomeStruct {} + +struct AnotherStruct { + field ?SomeType = 'default_string' +} + +fn test_struct_field_option_type_with_default_value() { + s := AnotherStruct{} + println(s.field) + assert '${s.field}' == "Option(SomeType('default_string'))" +}