From 2641a55a638afe6b650c5fcf10e7be0461b2b1fe Mon Sep 17 00:00:00 2001 From: Felipe Pena Date: Mon, 3 Mar 2025 13:52:45 -0300 Subject: [PATCH] cgen: fix codegen for match on return (fix #23661) (#23851) --- vlib/v/gen/c/match.v | 3 +++ vlib/v/tests/match_on_return_test.v | 29 +++++++++++++++++++++++++++++ 2 files changed, 32 insertions(+) create mode 100644 vlib/v/tests/match_on_return_test.v diff --git a/vlib/v/gen/c/match.v b/vlib/v/gen/c/match.v index 772e6271f6..72a961adac 100644 --- a/vlib/v/gen/c/match.v +++ b/vlib/v/gen/c/match.v @@ -8,6 +8,9 @@ import v.util fn (mut g Gen) need_tmp_var_in_match(node ast.MatchExpr) bool { if node.is_expr && node.return_type != ast.void_type && node.return_type != 0 { + if g.inside_struct_init { + return true + } if g.table.sym(node.return_type).kind in [.sum_type, .multi_return] || node.return_type.has_option_or_result() { return true diff --git a/vlib/v/tests/match_on_return_test.v b/vlib/v/tests/match_on_return_test.v new file mode 100644 index 0000000000..f8cfc852df --- /dev/null +++ b/vlib/v/tests/match_on_return_test.v @@ -0,0 +1,29 @@ +struct Bauds { + standard bool + bauds u32 +} + +fn max(v u32) !u32 { + if v > 38400 { + return error('too fast') + } + return v +} + +fn new_bauds(bauds u32) !&Bauds { + return &Bauds{ + standard: match bauds { + 300, 600, 1200, 2400, 4800, 9600, 14400, 19200, 38400 { true } + else { false } + } + bauds: max(bauds)! + } +} + +fn test_main() { + t := new_bauds(310)! + assert '${t}' == '&Bauds{ + standard: false + bauds: 310 +}' +}