Skip to content

Commit

Permalink
parser: allow map cast syntax map[k]v(expr) (#23401)
Browse files Browse the repository at this point in the history
  • Loading branch information
felipensp authored Jan 7, 2025
1 parent 7078a2e commit 9fc8352
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 1 deletion.
15 changes: 14 additions & 1 deletion vlib/v/parser/parser.v
Original file line number Diff line number Diff line change
Expand Up @@ -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' {
Expand Down
25 changes: 25 additions & 0 deletions vlib/v/tests/map_cast_test.v
Original file line number Diff line number Diff line change
@@ -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
}

0 comments on commit 9fc8352

Please sign in to comment.