From f4b39fbe4f77ad522b333285737dcc67da1a40b5 Mon Sep 17 00:00:00 2001 From: yuyi Date: Thu, 7 Jul 2022 02:03:42 +0800 Subject: [PATCH] cgen: fix sumtype with `none` (#14965) --- vlib/v/gen/c/cgen.v | 6 +++++- vlib/v/tests/sumtype_with_none_test.v | 18 ++++++++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) create mode 100644 vlib/v/tests/sumtype_with_none_test.v diff --git a/vlib/v/gen/c/cgen.v b/vlib/v/gen/c/cgen.v index 38ef07c695..b448f8698c 100644 --- a/vlib/v/gen/c/cgen.v +++ b/vlib/v/gen/c/cgen.v @@ -2078,7 +2078,11 @@ fn (mut g Gen) call_cfn_for_casting_expr(fname string, expr ast.Expr, exp_is_ptr g.write('&') } } - g.expr(expr) + if got_styp == 'none' && !g.cur_fn.return_type.has_flag(.optional) { + g.write('(none){EMPTY_STRUCT_INITIALIZATION}') + } else { + g.expr(expr) + } g.write(')'.repeat(rparen_n)) } diff --git a/vlib/v/tests/sumtype_with_none_test.v b/vlib/v/tests/sumtype_with_none_test.v new file mode 100644 index 0000000000..48c986426d --- /dev/null +++ b/vlib/v/tests/sumtype_with_none_test.v @@ -0,0 +1,18 @@ +module main + +fn string_none() string | none { + return none +} + +fn test_sumtype_with_none() { + x := string_none() + res := match x { + string { + false + } + none { + true + } + } + assert res +}