diff --git a/vlib/v/gen/cgen.v b/vlib/v/gen/cgen.v index 82ec040383..c43caf9170 100644 --- a/vlib/v/gen/cgen.v +++ b/vlib/v/gen/cgen.v @@ -4519,7 +4519,7 @@ fn (mut g Gen) return_statement(node ast.Return) { } } for i, expr in node.exprs { - g.expr(expr) + g.expr_with_cast(expr, node.types[i], g.fn_decl.return_type.clear_flag(.optional)) if i < node.exprs.len - 1 { g.write(', ') } @@ -5299,7 +5299,7 @@ fn (mut g Gen) or_block(var_name string, or_block ast.OrExpr, return_type table. if is_opt_call { g.write('*($mr_styp*) ') } - g.expr(expr_stmt.expr) + g.expr_with_cast(expr_stmt.expr, expr_stmt.typ, return_type.clear_flag(.optional)) if is_opt_call { g.write('.data') } diff --git a/vlib/v/tests/option_test.v b/vlib/v/tests/option_test.v index ce308b3b48..3f7ab6a9e0 100644 --- a/vlib/v/tests/option_test.v +++ b/vlib/v/tests/option_test.v @@ -323,16 +323,52 @@ fn test_option_void_return_types_of_anon_fn_in_struct() { } } -fn get_string(param bool) ?string { - if param { - return 'Hello World' - } - return none +type AA = BB | CC + +struct BB { + str string } -fn test_option_auto_add_return_none() { - r := get_string(false) or { - 'test' - } - assert r == 'test' +struct CC { + str string +} + +fn optional_sum_type(a int) ?AA { + match a { + 1 { + return BB{'Test'} + } + 2 { + return CC{'Test'} + } + else { + return error('Wrong number') + } + } +} + +fn test_optional_sum_type() { + res1 := optional_sum_type(1) or { + assert false + BB{} + } + res2 := optional_sum_type(2) or { + assert false + CC{} + } + if res1 is BB { + assert res1.str == 'Test' + } else { + assert false + } + if res2 is CC { + assert res2.str == 'Test' + } else { + assert false + } + optional_sum_type(3) or { + assert true + return + } + assert false }