Sisu
E0067

Array filled with one object

Error

Built from the repository at commit a8614dc.

[value; n] makes an array of n copies of value. When value is an object, or an optional of one, every copy is a reference to the same object.

Why

A change through one element would show in every element, which is almost never what a program means. To give each element an object of its own, start from None and fill the array in a loop.

When value's type is a type parameter T, T may stand for a class, and then every element would be the same object too, so [value; n] is an error there as well. [None; n], of type [T?], is not.

Broken

class Node {
    value: i64
}

fn main() {
    let nodes = [Node(value: 0); 3]
    print(nodes.len())
}

What sisu says

error[E0067]: every element would be the same `Node` object
 --> E0067.sisu:6:18
  |
6 |     let nodes = [Node(value: 0); 3]
  |                  ^^^^^^^^^^^^^^
  |
  = help: start from `[None; n]` with type `[Node?]` and fill it in a loop

sisu: 1 error
sisu: for more on a code, run `sisu explain <code>`: E0067

Fixed

class Node {
    value: i64
}

fn main() {
    let mut nodes: [Node?] = [None; 3]
    for i in 0..3 {
        nodes[i] = Node(value: i)
    }
    print(nodes[2]?.value ?? 0)
}