From ead0dff55a3981ea0ecaac6712caf3748e4522be Mon Sep 17 00:00:00 2001 From: yuyi Date: Sat, 20 Mar 2021 10:53:47 +0800 Subject: [PATCH] cgen: fix return if_guard expr (#9375) --- vlib/v/gen/c/cgen.v | 3 +++ vlib/v/tests/if_guard_test.v | 19 +++++++++++++++++++ 2 files changed, 22 insertions(+) diff --git a/vlib/v/gen/c/cgen.v b/vlib/v/gen/c/cgen.v index 3cb0bb07ee..17bd46a225 100644 --- a/vlib/v/gen/c/cgen.v +++ b/vlib/v/gen/c/cgen.v @@ -4357,6 +4357,9 @@ fn (mut g Gen) need_tmp_var_in_if(node ast.IfExpr) bool { return true } for branch in node.branches { + if branch.cond is ast.IfGuardExpr { + return true + } if branch.stmts.len == 1 { if branch.stmts[0] is ast.ExprStmt { stmt := branch.stmts[0] as ast.ExprStmt diff --git a/vlib/v/tests/if_guard_test.v b/vlib/v/tests/if_guard_test.v index bbd5e2624b..77f8ae11e1 100644 --- a/vlib/v/tests/if_guard_test.v +++ b/vlib/v/tests/if_guard_test.v @@ -59,3 +59,22 @@ fn test_chan_pop() { assert res == [6.75, -3.25, -37.5] } +struct Thing { + name string +} + +fn test_return_if_guard() { + ret := option_check('zoo') + println(ret) + assert ret == 'zs' +} + +fn option_check(name string) string { + return if thing := find_thing_by_name(name) { thing.name } else { 'safename' } +} + +fn find_thing_by_name(name string) ?&Thing { + return &Thing{ + name: 'zs' + } +}