diff --git a/vlib/v/checker/checker.v b/vlib/v/checker/checker.v index 0be5cdb743..678283d53e 100644 --- a/vlib/v/checker/checker.v +++ b/vlib/v/checker/checker.v @@ -5364,7 +5364,7 @@ pub fn (mut c Checker) match_expr(mut node ast.MatchExpr) ast.Type { } expr_type := c.expr(stmt.expr) if ret_type == ast.void_type { - if node.is_expr + if node.is_expr && !node.expected_type.has_flag(.optional) && c.table.get_type_symbol(node.expected_type).kind == .sum_type { ret_type = node.expected_type } else { diff --git a/vlib/v/tests/match_expr_returning_optional_test.v b/vlib/v/tests/match_expr_returning_optional_test.v new file mode 100644 index 0000000000..5156ac932a --- /dev/null +++ b/vlib/v/tests/match_expr_returning_optional_test.v @@ -0,0 +1,36 @@ +type Any = int | string + +fn ok(s string) Any { + return match s { + 'foo' { + Any(1) + } + else { + Any('asdf') + } + } +} + +fn fails(s string) ?Any { + return match s { + 'foo' { + Any(1) + } + else { + Any('asdf') + } + } +} + +fn test_match_expr_returning_optional() { + ret1 := ok('foo') + println(ret1) + assert ret1 == Any(1) + + ret2 := fails('foo') or { + assert false + return + } + println(ret2) + assert ret2 == Any(1) +}