checker: add a check for str[i] = `a` (#6107)

pull/6112/head
Swastik Baranwal 2020-08-11 21:11:54 +05:30 committed by GitHub
parent 99798b83b4
commit 9fdb1701e0
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 13 additions and 0 deletions

View File

@ -3076,6 +3076,9 @@ pub fn (mut c Checker) index_expr(mut node ast.IndexExpr) table.Type {
typ_sym.name.ends_with('ptr')) && !typ.has_flag(.variadic) { // byteptr, charptr etc
c.error('type `$typ_sym.name` does not support indexing', node.pos)
}
if typ_sym.kind == .string && !typ.is_ptr() && node.is_setter {
c.error('cannot assign to s[i] (strings are immutable)', node.pos)
}
if !c.inside_unsafe && (typ.is_ptr() || typ.is_pointer()) {
mut is_ok := false
if node.left is ast.Ident {

View File

@ -0,0 +1,6 @@
vlib/v/checker/tests/string_index_assign_error.v:3:6: error: cannot assign to s[i] (strings are immutable)
1 | fn main() {
2 | mut a := 'V is great!!'
3 | a[0] = `R`
| ~~~
4 | }

View File

@ -0,0 +1,4 @@
fn main() {
mut a := 'V is great!!'
a[0] = `R`
}