From d9689712f877ae19a031c7438170545de85ce023 Mon Sep 17 00:00:00 2001 From: Felipe Pena Date: Tue, 2 Jan 2024 14:57:48 -0300 Subject: [PATCH] cgen: fix option initialization with default struct initialization to not be `none` (#20349) --- vlib/v/gen/c/cgen.v | 3 ++- vlib/v/tests/option_ptr_init_empty_test.v | 30 +++++++++++++++++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) create mode 100644 vlib/v/tests/option_ptr_init_empty_test.v diff --git a/vlib/v/gen/c/cgen.v b/vlib/v/gen/c/cgen.v index 293e28e2a8f908..6a16bf5a99595a 100644 --- a/vlib/v/gen/c/cgen.v +++ b/vlib/v/gen/c/cgen.v @@ -1980,7 +1980,8 @@ fn (mut g Gen) expr_with_tmp_var(expr ast.Expr, expr_typ ast.Type, ret_typ ast.T // option ptr assignment simplification if is_ptr_to_ptr_assign { g.write('${tmp_var} = ') - } else if expr is ast.PrefixExpr && expr.right is ast.StructInit + } else if expr_typ.has_flag(.option) && expr is ast.PrefixExpr + && expr.right is ast.StructInit && (expr.right as ast.StructInit).init_fields.len == 0 { g.write('_option_none(&(${styp}[]) { ') } else { diff --git a/vlib/v/tests/option_ptr_init_empty_test.v b/vlib/v/tests/option_ptr_init_empty_test.v new file mode 100644 index 00000000000000..96ce416dab835e --- /dev/null +++ b/vlib/v/tests/option_ptr_init_empty_test.v @@ -0,0 +1,30 @@ +pub struct Test { + a int = 10 + b int = 5 +} + +pub struct ABC { + test ?&Test + test2 ?Test +} + +fn test_main() { + abc := ABC{ + test: &Test{} // non option init + test2: Test{} // non option init + } + + if ttt := abc.test { + assert ttt.a == 10 + assert ttt.b == 5 + } else { + assert false + } + + if ttt := abc.test2 { + assert ttt.a == 10 + assert ttt.b == 5 + } else { + assert false + } +}