1
0
mirror of https://github.com/vlang/v.git synced 2023-08-10 21:13:21 +03:00

parser: support short struct update syntax {...ident, (#8613)

This commit is contained in:
Nick Treleaven 2021-02-07 02:43:51 +00:00 committed by GitHub
parent b92f980274
commit cd4f7101f7
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 8 additions and 3 deletions

View File

@ -1633,6 +1633,8 @@ Only more complex types such as arrays and maps may be modified.
Use `user.register()` or `user = register(user)`
instead of `register(mut user)`.
#### Struct update syntax
V makes it easy to return a modified version of an object:
```v
@ -1644,7 +1646,7 @@ struct User {
fn register(u User) User {
return {
u |
...u
is_registered: true
}
}

View File

@ -246,7 +246,8 @@ pub fn (mut p Parser) expr(precedence int) ast.Expr {
// it should be a struct
if p.peek_tok.kind == .pipe {
node = p.assoc()
} else if p.peek_tok.kind == .colon || p.tok.kind in [.rcbr, .comment] {
} else if (p.tok.kind == .name && p.peek_tok.kind == .colon)
|| p.tok.kind in [.rcbr, .comment, .ellipsis] {
node = p.struct_init(true) // short_syntax: true
} else if p.tok.kind == .name {
p.next()

View File

@ -164,12 +164,14 @@ fn test_assoc_with_vars() {
def2 := Def{
a: 12
}
merged := Def{
mut merged := Def{
...def2
a: 42
}
assert merged.a == 42
assert merged.b == 7
merged = {...def2, b: 9}
assert merged == Def{12, 9}
def3 := &Def{ 100, 200 }
merged1 := Def{...(*def3)}