diff --git a/vlib/v/checker/checker.v b/vlib/v/checker/checker.v index afe127b7a0..6b838c050c 100644 --- a/vlib/v/checker/checker.v +++ b/vlib/v/checker/checker.v @@ -3219,7 +3219,14 @@ pub fn (mut c Checker) ident(mut ident ast.Ident) table.Type { return table.void_type } } - typ = c.expr(obj.expr) + if mut obj.expr is ast.IfGuardExpr { + // new variable from if guard shouldn't have the optional flag for further use + // a temp variable will be generated which unwraps it + if_guard_var_type := c.expr(obj.expr.expr) + typ = if_guard_var_type.clear_flag(.optional) + } else { + typ = c.expr(obj.expr) + } } is_optional := typ.has_flag(.optional) ident.kind = .variable diff --git a/vlib/v/gen/cgen.v b/vlib/v/gen/cgen.v index d1674746a3..834ac4ea16 100644 --- a/vlib/v/gen/cgen.v +++ b/vlib/v/gen/cgen.v @@ -3544,7 +3544,8 @@ fn (mut g Gen) if_expr(node ast.IfExpr) { g.expr(branch.cond.expr) g.writeln(', ${var_name}.ok) {') if branch.cond.var_name != '_' { - g.writeln('\t${g.typ(branch.cond.expr_type)} $branch.cond.var_name = $var_name;') + base_type := g.base_type(branch.cond.expr_type) + g.writeln('\t$base_type $branch.cond.var_name = *($base_type*)${var_name}.data;') } } else { diff --git a/vlib/v/parser/if_match.v b/vlib/v/parser/if_match.v index 8b8a029c92..295404b989 100644 --- a/vlib/v/parser/if_match.v +++ b/vlib/v/parser/if_match.v @@ -106,15 +106,15 @@ fn (mut p Parser) if_expr(is_comptime bool) ast.IfExpr { p.check(.decl_assign) comments << p.eat_comments() expr := p.expr(0) - p.scope.register(var_name, ast.Var{ - name: var_name - expr: expr - pos: var_pos - }) cond = ast.IfGuardExpr{ var_name: var_name expr: expr } + p.scope.register(var_name, ast.Var{ + name: var_name + expr: cond + pos: var_pos + }) prev_guard = true } else { prev_guard = false