diff --git a/vlib/v/checker/if.v b/vlib/v/checker/if.v index 8fdb52a91d..dff625ac3d 100644 --- a/vlib/v/checker/if.v +++ b/vlib/v/checker/if.v @@ -327,7 +327,7 @@ fn (mut c Checker) if_expr(mut node ast.IfExpr) ast.Type { node.pos) } } - } else if !node.is_comptime { + } else if !node.is_comptime && stmt !is ast.Return { c.error('`${if_kind}` expression requires an expression as the last statement of every branch', branch.pos) } diff --git a/vlib/v/tests/return_error_in_if_expr_test.v b/vlib/v/tests/return_error_in_if_expr_test.v new file mode 100644 index 0000000000..27ba9bf6f1 --- /dev/null +++ b/vlib/v/tests/return_error_in_if_expr_test.v @@ -0,0 +1,25 @@ +struct NotFoundError { + Error +} + +fn get_username() !string { + return NotFoundError{} +} + +fn print_username() !string { + username := get_username() or { + if err is NotFoundError { + 'test' + } else { + return err + } + } + + println(username) + return username +} + +fn test_return_err_in_if_expr() { + ret := print_username()! + assert ret == 'test' +}