Skip to content

Commit

Permalink
cgen: fix generated code for assignments of if ternary non-opt valu…
Browse files Browse the repository at this point in the history
…es to an option struct member (#19485)
  • Loading branch information
felipensp authored Oct 20, 2023
1 parent 90f6010 commit b3d1b04
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 1 deletion.
6 changes: 5 additions & 1 deletion vlib/v/gen/c/cgen.v
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
15 changes: 15 additions & 0 deletions vlib/v/tests/if_assign_test.v
Original file line number Diff line number Diff line change
@@ -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'
}

0 comments on commit b3d1b04

Please sign in to comment.