From b3d1b041f8f1d3e90cef2b4135e5511e3fb2ceca Mon Sep 17 00:00:00 2001 From: Felipe Pena Date: Thu, 19 Oct 2023 22:51:42 -0300 Subject: [PATCH] cgen: fix generated code for assignments of `if` ternary non-opt values to an option struct member (#19485) --- vlib/v/gen/c/cgen.v | 6 +++++- vlib/v/tests/if_assign_test.v | 15 +++++++++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) create mode 100644 vlib/v/tests/if_assign_test.v diff --git a/vlib/v/gen/c/cgen.v b/vlib/v/gen/c/cgen.v index 8cb1cf4a793310..f037c78452a55e 100644 --- a/vlib/v/gen/c/cgen.v +++ b/vlib/v/gen/c/cgen.v @@ -1813,7 +1813,11 @@ fn (mut g Gen) stmts_with_tmp_var(stmts []ast.Stmt, tmp_var string) bool { g.expr(stmt.expr) g.writeln(';') } else { - ret_typ := g.fn_decl.return_type.clear_flag(.option) + ret_typ := if g.inside_assign { + stmt.typ + } else { + g.fn_decl.return_type.clear_flag(.option) + } styp = g.base_type(ret_typ) g.write('_option_ok(&(${styp}[]) { ') g.expr_with_cast(stmt.expr, stmt.typ, ret_typ) diff --git a/vlib/v/tests/if_assign_test.v b/vlib/v/tests/if_assign_test.v new file mode 100644 index 00000000000000..2fb087bda96dfd --- /dev/null +++ b/vlib/v/tests/if_assign_test.v @@ -0,0 +1,15 @@ +struct Foo { +mut: + option ?string +} + +fn test_main() { + mut foo := Foo{} + some_val := 1 + foo.option = if some_val > 0 { + 'awesome' + } else { + none + } + assert foo.option? == 'awesome' +}