1
0
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:
谢克 2022-12-08 17:08:39 +08:00 committed by GitHub
parent 2261606b56
commit 32c80c53b3
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 29 additions and 2 deletions

View File

@ -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} }')

View 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))
}