diff --git a/vlib/v/parser/parser.v b/vlib/v/parser/parser.v index 1ebdf85f2abe55..c78251bdc0d7d9 100644 --- a/vlib/v/parser/parser.v +++ b/vlib/v/parser/parser.v @@ -2719,10 +2719,23 @@ fn (mut p Parser) name_expr() ast.Expr { if is_option { map_type = map_type.set_flag(.option) } - return ast.MapInit{ + node = ast.MapInit{ typ: map_type pos: pos } + if p.tok.kind == .lpar { + // ?map[int]int(none) cast expr + p.check(.lpar) + expr := p.expr(0) + p.check(.rpar) + return ast.CastExpr{ + typ: map_type + typname: p.table.sym(map_type).name + expr: expr + pos: pos.extend(p.tok.pos()) + } + } + return node } // `chan typ{...}` if p.tok.lit == 'chan' { diff --git a/vlib/v/tests/map_cast_test.v b/vlib/v/tests/map_cast_test.v new file mode 100644 index 00000000000000..dc3fab0c0ecb45 --- /dev/null +++ b/vlib/v/tests/map_cast_test.v @@ -0,0 +1,25 @@ +fn foo() map[int]int { + return { + 1: 2 + } +} + +fn test_main() { + a := ?map[int]int(none) + assert a == none + + b := ?map[int]int({ + 1: 2 + }) + assert b?[1] == 2 + + c := ?map[int]map[string]string({ + 1: { + 'foo': 'bar' + } + }) + assert c?[1]['foo'] == 'bar' + + d := ?map[int]int(foo()) + assert d?[1] == 2 +}