mirror of
https://github.com/vlang/v.git
synced 2023-08-10 21:13:21 +03:00
cgen: fix generic functions returning none or error values with generic result types (#16613)
This commit is contained in:
parent
2261606b56
commit
32c80c53b3
@ -4387,7 +4387,7 @@ fn (g &Gen) expr_is_multi_return_call(expr ast.Expr) bool {
|
||||
}
|
||||
|
||||
fn (mut g Gen) gen_result_error(target_type ast.Type, expr ast.Expr) {
|
||||
styp := g.typ(target_type)
|
||||
styp := g.typ(g.unwrap_generic(target_type))
|
||||
g.write('(${styp}){ .is_error=true, .err=')
|
||||
g.expr(expr)
|
||||
g.write(', .data={EMPTY_STRUCT_INITIALIZATION} }')
|
||||
@ -4395,7 +4395,7 @@ fn (mut g Gen) gen_result_error(target_type ast.Type, expr ast.Expr) {
|
||||
|
||||
// NB: remove this when optional has no errors anymore
|
||||
fn (mut g Gen) gen_optional_error(target_type ast.Type, expr ast.Expr) {
|
||||
styp := g.typ(target_type)
|
||||
styp := g.typ(g.unwrap_generic(target_type))
|
||||
g.write('(${styp}){ .state=2, .err=')
|
||||
g.expr(expr)
|
||||
g.write(', .data={EMPTY_STRUCT_INITIALIZATION} }')
|
||||
|
27
vlib/v/tests/generic_fn_returning_option_and_result_test.v
Normal file
27
vlib/v/tests/generic_fn_returning_option_and_result_test.v
Normal file
@ -0,0 +1,27 @@
|
||||
module main
|
||||
|
||||
fn get_value[T]() ?T {
|
||||
return none
|
||||
}
|
||||
|
||||
fn get_value_result[T]() !T {
|
||||
return error('no result')
|
||||
}
|
||||
|
||||
fn test_generic_function_that_returns_an_option() {
|
||||
value := get_value[&int]() or { &int(0) }
|
||||
assert value == unsafe { nil }
|
||||
sval := get_value[string]() or { 'abc' }
|
||||
assert sval == 'abc'
|
||||
uval := get_value[u64]() or { 123 }
|
||||
assert uval == 123
|
||||
}
|
||||
|
||||
fn test_generic_function_that_returns_an_error() {
|
||||
sval := get_value_result[string]() or { 'xyz' }
|
||||
assert sval == 'xyz'
|
||||
ival := get_value_result[int]() or { 456 }
|
||||
assert ival == 456
|
||||
pval := get_value_result[&int]() or { &int(789) }
|
||||
assert u64(pval) == u64(&int(789))
|
||||
}
|
Loading…
Reference in New Issue
Block a user