Skip to content

Commit 32c80c5

Browse files
authored
cgen: fix generic functions returning none or error values with generic result types (#16613)
1 parent 2261606 commit 32c80c5

File tree

2 files changed

+29
-2
lines changed

2 files changed

+29
-2
lines changed

vlib/v/gen/c/cgen.v

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4387,15 +4387,15 @@ fn (g &Gen) expr_is_multi_return_call(expr ast.Expr) bool {
43874387
}
43884388

43894389
fn (mut g Gen) gen_result_error(target_type ast.Type, expr ast.Expr) {
4390-
styp := g.typ(target_type)
4390+
styp := g.typ(g.unwrap_generic(target_type))
43914391
g.write('(${styp}){ .is_error=true, .err=')
43924392
g.expr(expr)
43934393
g.write(', .data={EMPTY_STRUCT_INITIALIZATION} }')
43944394
}
43954395

43964396
// NB: remove this when optional has no errors anymore
43974397
fn (mut g Gen) gen_optional_error(target_type ast.Type, expr ast.Expr) {
4398-
styp := g.typ(target_type)
4398+
styp := g.typ(g.unwrap_generic(target_type))
43994399
g.write('(${styp}){ .state=2, .err=')
44004400
g.expr(expr)
44014401
g.write(', .data={EMPTY_STRUCT_INITIALIZATION} }')
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
module main
2+
3+
fn get_value[T]() ?T {
4+
return none
5+
}
6+
7+
fn get_value_result[T]() !T {
8+
return error('no result')
9+
}
10+
11+
fn test_generic_function_that_returns_an_option() {
12+
value := get_value[&int]() or { &int(0) }
13+
assert value == unsafe { nil }
14+
sval := get_value[string]() or { 'abc' }
15+
assert sval == 'abc'
16+
uval := get_value[u64]() or { 123 }
17+
assert uval == 123
18+
}
19+
20+
fn test_generic_function_that_returns_an_error() {
21+
sval := get_value_result[string]() or { 'xyz' }
22+
assert sval == 'xyz'
23+
ival := get_value_result[int]() or { 456 }
24+
assert ival == 456
25+
pval := get_value_result[&int]() or { &int(789) }
26+
assert u64(pval) == u64(&int(789))
27+
}

0 commit comments

Comments
 (0)