diff --git a/vlib/v/checker/containers.v b/vlib/v/checker/containers.v index 3a046e1c2c95ef..dd80469ea859cb 100644 --- a/vlib/v/checker/containers.v +++ b/vlib/v/checker/containers.v @@ -119,8 +119,12 @@ fn (mut c Checker) array_init(mut node ast.ArrayInit) ast.Type { // `a = []` if node.exprs.len == 0 { // `a := fn_returning_opt_array() or { [] }` - if c.expected_type == ast.void_type && c.expected_or_type != ast.void_type { - c.expected_type = c.expected_or_type + if c.expected_type == ast.void_type { + if c.expected_or_type != ast.void_type { + c.expected_type = c.expected_or_type + } else if c.expected_expr_type != ast.void_type { + c.expected_type = c.expected_expr_type + } } mut type_sym := c.table.sym(c.expected_type) if type_sym.kind != .array || type_sym.array_info().elem_type == ast.void_type { diff --git a/vlib/v/checker/match.v b/vlib/v/checker/match.v index 191d002f470b11..40bf3f274be902 100644 --- a/vlib/v/checker/match.v +++ b/vlib/v/checker/match.v @@ -66,7 +66,11 @@ fn (mut c Checker) match_expr(mut node ast.MatchExpr) ast.Type { if branch.stmts.len > 0 && node.is_expr { mut stmt := branch.stmts.last() if mut stmt is ast.ExprStmt { - c.expected_type = node.expected_type + c.expected_type = if c.expected_expr_type != ast.void_type { + c.expected_expr_type + } else { + node.expected_type + } expr_type := if stmt.expr is ast.CallExpr { stmt.typ } else { @@ -92,6 +96,7 @@ fn (mut c Checker) match_expr(mut node ast.MatchExpr) ast.Type { } } } + c.expected_expr_type = expr_type } infer_cast_type = stmt.typ if mut stmt.expr is ast.CastExpr { diff --git a/vlib/v/tests/conditions/matches/match_expr_with_empty_array_init_test.v b/vlib/v/tests/conditions/matches/match_expr_with_empty_array_init_test.v new file mode 100644 index 00000000000000..0eccce596c4b5c --- /dev/null +++ b/vlib/v/tests/conditions/matches/match_expr_with_empty_array_init_test.v @@ -0,0 +1,18 @@ +fn test_match_expr_with_empty_array_init() { + arr1 := ['Peter', 'Bob'] + arr2 := ['Sam', 'Mike'] + typ := 1 + names := match typ { + 1 { + arr1 + } + 2 { + arr2 + } + else { + [] + } + } + println(names) + assert names == ['Peter', 'Bob'] +}