vfmt: support `a[i] or { panic(err) }` too
parent
7037965973
commit
24d1ec2714
32
doc/docs.md
32
doc/docs.md
|
@ -718,36 +718,46 @@ println(m['one']) // "1"
|
||||||
println(m['bad_key']) // "0"
|
println(m['bad_key']) // "0"
|
||||||
println('bad_key' in m) // Use `in` to detect whether such key exists
|
println('bad_key' in m) // Use `in` to detect whether such key exists
|
||||||
m.delete('two')
|
m.delete('two')
|
||||||
// Short syntax
|
// NB: map keys can have any type, `int` in this case,
|
||||||
|
// and the whole map can be initialized using this short syntax:
|
||||||
numbers := {
|
numbers := {
|
||||||
1: 'two' // map keys can have any type, `int` in this case
|
1: 'one'
|
||||||
2: 'three'
|
2: 'two'
|
||||||
}
|
}
|
||||||
|
println(numbers)
|
||||||
```
|
```
|
||||||
|
|
||||||
If a key is not found, a zero value is returned by default:
|
If a key is not found, a zero value is returned by default:
|
||||||
|
|
||||||
```v
|
```v
|
||||||
val := m['bad_key']
|
sm := {
|
||||||
println(val) // 0
|
'abc': 'xyz'
|
||||||
|
}
|
||||||
s := numbers[3]
|
val := sm['bad_key']
|
||||||
println(s) // ""
|
println(val) // ''
|
||||||
|
intm := {
|
||||||
|
1: 1234
|
||||||
|
2: 5678
|
||||||
|
}
|
||||||
|
s := intm[3]
|
||||||
|
println(s) // 0
|
||||||
```
|
```
|
||||||
|
|
||||||
It's also possible to use an `or {}` block to handle missing keys:
|
It's also possible to use an `or {}` block to handle missing keys:
|
||||||
|
|
||||||
```v
|
```v
|
||||||
val := m['bad_key'] or { println('key not found') }
|
mm := map[string]int{}
|
||||||
|
val := mm['bad_key'] or { panic('key not found') }
|
||||||
```
|
```
|
||||||
|
|
||||||
The same optional check applies to arrays:
|
The same optional check applies to arrays:
|
||||||
|
|
||||||
```v
|
```v
|
||||||
val := arr[large_index] or { println('out of bounds') }
|
arr := [1, 2, 3]
|
||||||
|
large_index := 999
|
||||||
|
val := arr[large_index] or { panic('out of bounds') }
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|
||||||
## Module imports
|
## Module imports
|
||||||
|
|
||||||
For information about creating a module, see [Modules](#modules).
|
For information about creating a module, see [Modules](#modules).
|
||||||
|
|
|
@ -1222,6 +1222,9 @@ pub fn (mut f Fmt) index_expr(node ast.IndexExpr) {
|
||||||
f.write('[')
|
f.write('[')
|
||||||
f.expr(node.index)
|
f.expr(node.index)
|
||||||
f.write(']')
|
f.write(']')
|
||||||
|
if node.or_expr.kind != .absent {
|
||||||
|
f.or_expr(node.or_expr)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn (mut f Fmt) par_expr(node ast.ParExpr) {
|
pub fn (mut f Fmt) par_expr(node ast.ParExpr) {
|
||||||
|
|
Loading…
Reference in New Issue