V: iterator t over an array of Struct is implicitly mutable, however throws an error when calling function which mutates the muteable value.

Created on 11 Oct 2019  路  4Comments  路  Source: vlang/v

V version: V 0.1.21 72ae128
OS: Solus 4.0

What did you do?
Compile and run the following:

struct Test {
    mut:
        s string
}

fn (a mut Test) set_to_a() {
    a.s = 'A'
}

fn main() {
    b := Test {s:'B'}
    c := Test {s:'C'}
    teststrings := [b,c]
    for t in teststrings {
        t.set_to_a()
        println(t.s)
    }
}

What did you expect to see?

A
A

What did you see instead?

test.v:15:19: `t` is immutable, declare it with `mut`
   14|     for t in teststrings {
   15|         t.set_to_a()
                         ^
   16|         println(t.s)
   17|     }
Bug

Most helpful comment

I've updated the error. It now states that for variables are always immutable.

All 4 comments

for variables are always immutable:

https://vlang.io/docs#for

The error should be changed a bit, since it's not possible to use mut here.

@ArjenR Correct way to do it in V is:

fn main() {
    b := Test {s:'B'}
    c := Test {s:'C'}
    mut teststrings := [b,c]
    for i, _ in teststrings {
        teststrings[i].set_to_a()
        println(teststrings[i].s)
    }
}

Note that you also have to make testsrings mutable.

I'm still sceptical about support of the traditional C style for loop

I've updated the error. It now states that for variables are always immutable.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

taojy123 picture taojy123  路  3Comments

XVilka picture XVilka  路  3Comments

lobotony picture lobotony  路  3Comments

arg2das picture arg2das  路  3Comments

cjmxp picture cjmxp  路  3Comments