Lyricdev
GitHub

LYR-SEM0116

'with' on something other than a struct

error · spec 03-types

The target of 'with' is not a struct — a class, a tuple, another type — or a path inside its field list reaches through a field that is no struct.

Explanation

p with { x = 1 } copies a struct value and replaces the named fields. It is defined for structs only, and a path (p with { pos.x = 1 }) reaches through struct fields only, because each step is a copy of a value. An object of a class has an identity and is changed in place or cloned; a tuple has no field names.

Change the type to a struct, assign the class's field in place (on a clone when the original must stay), or build a new tuple.

Wrong

class Holder { var n: int }

fn main(): void {
    let h = Holder { n = 0 };
    let g = h with { n = 1 };
    let _ = g.n;
}
struct Holder { n: int }

fn main(): void {
    let h = Holder { n = 0 };
    let g = h with { n = 1 };
    let _ = g.n;
}