diff --git a/vlib/v/checker/checker.v b/vlib/v/checker/checker.v index 01fff0cf36..3500747b8f 100644 --- a/vlib/v/checker/checker.v +++ b/vlib/v/checker/checker.v @@ -1258,6 +1258,11 @@ pub fn (mut c Checker) return_stmt(mut return_stmt ast.Return) { } for i, exp_type in expected_types { got_typ := got_types[i] + if got_typ.flag_is(.optional) && + (!exp_type.flag_is(.optional) || c.table.type_to_str(got_typ) != c.table.type_to_str(exp_type)) { + pos := return_stmt.exprs[i].position() + c.error('cannot use `${c.table.type_to_str(got_typ)}` as type `${c.table.type_to_str(exp_type)}` in return argument', pos) + } is_generic := exp_type == table.t_type ok := if is_generic { c.check_types(got_typ, c.cur_generic_type) || got_typ == exp_type } else { c.check_types(got_typ, exp_type) } diff --git a/vlib/v/checker/tests/return_optional_err.out b/vlib/v/checker/tests/return_optional_err.out new file mode 100644 index 0000000000..374d087dd9 --- /dev/null +++ b/vlib/v/checker/tests/return_optional_err.out @@ -0,0 +1,7 @@ +vlib/v/checker/tests/return_optional_err.v:4:13: error: cannot use `?string` as type `string` in return argument + 2 | + 3 | fn my_func() string { + 4 | return os.read_file('/some/file/that/exists.txt') or {panic(err)} + | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + 5 | } + 6 | diff --git a/vlib/v/checker/tests/return_optional_err.vv b/vlib/v/checker/tests/return_optional_err.vv new file mode 100644 index 0000000000..3bcda19257 --- /dev/null +++ b/vlib/v/checker/tests/return_optional_err.vv @@ -0,0 +1,10 @@ +import os + +fn my_func() string { + return os.read_file('/some/file/that/exists.txt') or {panic(err)} +} + +fn main() { + aa := my_func() + println(aa) +}