diff --git a/vlib/v/checker/checker.v b/vlib/v/checker/checker.v index 76a053d583..43084a438f 100644 --- a/vlib/v/checker/checker.v +++ b/vlib/v/checker/checker.v @@ -5027,6 +5027,13 @@ pub fn (mut c Checker) if_expr(mut node ast.IfExpr) table.Type { } continue } + if c.expected_type.has_flag(.generic) { + if node.typ == table.void_type { + node.is_expr = true + node.typ = c.unwrap_generic(c.expected_type) + } + continue + } last_expr.typ = c.expr(last_expr.expr) if !c.check_types(last_expr.typ, node.typ) { if node.typ == table.void_type { diff --git a/vlib/v/tests/if_expression_test.v b/vlib/v/tests/if_expression_test.v index b127c9c7fe..7603c3dc32 100644 --- a/vlib/v/tests/if_expression_test.v +++ b/vlib/v/tests/if_expression_test.v @@ -22,11 +22,7 @@ fn test_if_expression_with_stmts() { } assert a == 1 mut b := 0 - b = if false { - 42 - } else { - 24 - } + b = if false { 42 } else { 24 } assert b == 24 } @@ -164,18 +160,22 @@ fn test_if_expr_with_infix() { } fn test_multi_if_expr_with_infix() { - a := if 1 == 0 { 1 } else if 1 == 0 { 2 } else { 3 } + 4 + a := if 1 == 0 { + 1 + } else if 1 == 0 { + 2 + } else { + 3 + } + 4 assert a == 7 } fn test_if_expr_with_array_map() { num_string := '2 3' - assigned := if num_string.len > 1 { - num_string.split(' ').map(it.int()) - } else { - [789] - } + assigned := if num_string.len > 1 { num_string.split(' ').map(it.int()) } else { [ + 789, + ] } println(assigned) assert assigned == [2, 3] @@ -191,3 +191,11 @@ fn test_if_epxr_with_array_conditions() { assert false } } + +fn min(a T, b T) T { + return if a < b { a } else { b } +} + +fn test_if_expr_with_fn_generic() { + assert min(42, 13) == 13 +}