Skip to content

Commit d9cca53

Browse files
authored
checker: check error for index of optional (#13785)
1 parent 21e9b1d commit d9cca53

File tree

3 files changed

+18
-0
lines changed

3 files changed

+18
-0
lines changed

vlib/v/checker/checker.v

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3775,6 +3775,9 @@ pub fn (mut c Checker) index_expr(mut node ast.IndexExpr) ast.Type {
37753775
&& typ !in [ast.byteptr_type, ast.charptr_type] && !typ.has_flag(.variadic) {
37763776
c.error('type `$typ_sym.name` does not support indexing', node.pos)
37773777
}
3778+
if typ.has_flag(.optional) {
3779+
c.error('type `?$typ_sym.name` is optional, it does not support indexing', node.left.pos())
3780+
}
37783781
if typ_sym.kind == .string && !typ.is_ptr() && node.is_setter {
37793782
c.error('cannot assign to s[i] since V strings are immutable\n' +
37803783
'(note, that variables may be mutable but string values are always immutable, like in Go and Java)',
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
vlib/v/checker/tests/index_of_optional_err.vv:6:7: error: type `?[]int` is optional, it does not support indexing
2+
4 |
3+
5 | fn main() {
4+
6 | a := abc()[0] or { 5 }
5+
| ~~~~~
6+
7 | dump(a)
7+
8 | }
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
fn abc() ?[]int {
2+
return [1, 2, 3]
3+
}
4+
5+
fn main() {
6+
a := abc()[0] or { 5 }
7+
dump(a)
8+
}

0 commit comments

Comments
 (0)