cgen: fix generated code for assignments of if ternary non-opt values to an option struct member (#19485)

This commit is contained in:
Felipe Pena 2023-10-19 22:51:42 -03:00 committed by GitHub
parent 90f6010ef7
commit b3d1b041f8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 20 additions and 1 deletions

View File

@ -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)

View File

@ -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'
}