Lyricdev
GitHub

LYR-SEM0136

a repeated array literal of an element that would need cloning

error · spec 03-types

'[x] * n' repeats an element that is or holds an object (or may, in a generic body), and the element type does not conform to 'Clone'.

Explanation

[x] * n fills n slots. A value element is copied; an element that is or holds an object is cloned into every slot, never shared, because n aliases of one object are rarely what is meant. Cloning needs the element type to conform to Clone.

Declare Clone on the element type, or build the array with arrayOf(n, (i) => …), which makes a fresh element per slot.

Wrong

class Cell { v: int }

fn main(): void {
    let xs = [Cell { v = 1 }] * 3;
    let _ = xs.length();
}
import std.core { arrayOf };

class Cell { v: int }

fn main(): void {
    let xs = arrayOf(3, (i) => Cell { v = 1 });
    let _ = xs.length();
}