diff --git a/vlib/v/gen/c/cgen.v b/vlib/v/gen/c/cgen.v index 4601417024..7a4e2d8272 100644 --- a/vlib/v/gen/c/cgen.v +++ b/vlib/v/gen/c/cgen.v @@ -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} }') diff --git a/vlib/v/tests/generic_fn_returning_option_and_result_test.v b/vlib/v/tests/generic_fn_returning_option_and_result_test.v new file mode 100644 index 0000000000..04111fb335 --- /dev/null +++ b/vlib/v/tests/generic_fn_returning_option_and_result_test.v @@ -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)) +}