V: For loop scope

Created on 7 Jan 2020  路  4Comments  路  Source: vlang/v

V version: 0.1.24 8c59232
OS: CentOS 7.6.1810 (gcc 6.3.0)

What did you do?

fn main() {
        a := [0]
        mut ans := [[]int]
        ans.delete(0)
        for i := 0; i < 3; i++ {
                mut b := a // <- b should be a distinct copy for each loop
                b << i
                ans << b
        }
        println(ans)
}

What did you expect to see?

[[0, 0], [0, 1], [0, 2]]

What did you see instead?

[[0, 2], [0, 2], [0, 2]]
Bug Confirmed Compiler

Most helpful comment

This particular case will work like in Rust.

All 4 comments

Related #119

mut b := a.clone() for right now probably

@emily33901 This is a reasonable solution, but I think that the default here is somehow counterintuitive. Either

  1. Default to copy when making a mutable reference to an immutable. (Not exactly the same, but in Go, b := a always copy)
  2. Or ask user to make a copy explicitly. In Rust let mut b = a defaults to move, and it will fail to compile in this case because in a loop move occurs more than once (User should explicitly state let mut b = a.clone()).

This particular case will work like in Rust.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

penguindark picture penguindark  路  3Comments

oleg-kachan picture oleg-kachan  路  3Comments

vtereshkov picture vtereshkov  路  3Comments

medvednikov picture medvednikov  路  3Comments

taojy123 picture taojy123  路  3Comments