Types
Reference vs value semantics
Which types are shared when assigned or passed (class instances) and which are copied (primitives, structs, arrays).
since 0.1.0-alpha.1linuxwindowswasm
Description
A type is either a reference type or a value type, and that decides what an assignment or a function call does with it.
- Instances of a
classare references. Assigning one to another variable, or passing it to a function, shares the same object. A change made through either name is visible through the other. - Primitives,
structvalues and arrays are values. Assigning or passing one makes an independent copy. A change to the copy does not affect the original.
Sharing versus copying
use io::console;
class Counter {
int n = 0;
}
struct Point {
int x = 0;
int y = 0;
}
void bumpClass(Counter c) { c.n = c.n + 1; }
void bumpInt(int n) { n = n + 1; }
void movePoint(Point p) { p.x = 99; }
Counter c1 = Counter();
Counter c2 = c1;
c2.n = 5;
bumpClass(c1);
console.writeln(c1.n);
int a = 1;
bumpInt(a);
console.writeln(a);
Point p1 = Point(1, 2);
Point p2 = p1;
p2.x = 10;
movePoint(p1);
console.writeln(p1.x);
6
1
1
Rules
- A class instance is shared by every variable, field, parameter and collection slot that refers to it.
- A primitive (
int,float,bool,char,string,decimaland the sized numeric types) is copied on assignment and when passed. - A
structis copied on assignment, on passing as an argument and when read out of a collection into a variable or an argument (P q = xs[0];). Mutating the copy leaves the original unchanged. - A place is a variable (a local, a parameter or a global),
this, a field of a place, an element or map value of a place (xs[0],m["k"]), and a property with both agetand asetaccessor reached through a place (an indexer with bothget ([])andset ([])too). A member of a class instance is a place wherever the instance came from, because the instance is shared. Everything else is a temporary: the result of a call (f(),xs.at(0),m.at("k")), of a construction (P(1)), of an operator or ofawait, the value of an assignment ((a = b)), the result of a?:, amatchor a??, a property or indexer with only agetaccessor, and a field or element of a temporary (f().p,f()[0]of an array thatfreturns). Whether a property has asetgoes by the type it is read through: throughinterface I { P get p(); }the property is a temporary, also when the object's class holdspin a plain field. The type a member is read through decides the shape of a store: a plain field or a property with asetis writable, and a store through it is get, change, set; the set is a member write and runs the setter of the object's own class if it has one; if the object's own class holds a plain field, the change made in place is the store and nothing else is written. This changes behaviour for existing programs: a store or amutatingcall through a plain field of the static view, on an object whose class holds an accessor pair of that name, now runs that class's setter with the changed value, where it used to change only the getter's temporary. A getter-only property of a definite collection type is a temporary like a struct: an index store through it, plain or compound (h.r[0] = 5,h.r[0] += 5withArray<int> get r()), is the same compile error, and only a maybe-typed temporary is unchecked (aT get r()that holds an array: the store lands in the temporary and the slot is unchanged). A compound storep op= eisp = p op e: the sub-expressions of the place (mk()andix()inmk().a[ix()] += 1) are evaluated once, and the place itself is read for the old value and again as the base of the store, so a getter on the way runs for the read and again for the store (mk().a[ix()] += 1with a pairarunsmk,ix, the getter, the getter, the setter: for an element, the root and the indices run first and the old value is read after the right-hand side, the element order in calls). - Mutating a temporary whose type is a struct is a compile error, because the change would be lost with the temporary: a
mutatingcall on it, a store to one of its fields or elements (plain or compound) and asetorset ([])accessor on it (xs.at(0).bump(),f().x = 3,(t ? a : b).x += 1,h.q.x = 3with onlyget q) reportcannot mutate a temporary 'P' (a call result): the change would be lost; store it in a variable first, naming the kind of temporary. A temporary whose type is an interface, an optional or a type parameter is not checked: mutating it is allowed, also when the type is an optional of a struct (mkp()?.bump()withP? mkp()). When it holds a struct, the change lands in the temporary, and the place it was read from, if any, is unchanged ((l = m).add(1)with interface-typedlandmchanges neither); when it holds a class instance, the instance changes. - A
structstored in a field is a place: calling amutatingmethod on it through the field (h.p.bump(),this.p.bump(), a barep.bump()inside the class, or a nesteda.b.c.bump()) changes that field in place, exactly as assigning through it (h.p.x = 5) does. An element of an array, and a value of a map, is a place in the same way:xs[0].x = 5,xs[0].x += 1,xs[0].p.x = 5,xs[0].bump(),xs[0].p.bump()andm["k"].bump()change the element in the collection. Such a write reads the element, changes it and stores it back into the collection, so another array that shares the same contents (Array<P> ys = xs;) keeps the old element, and amutatingmethod that throws keeps the changes it made before the throw. An element whose declared type is an interface, a generic or an optional type is a place in the same way when it holds a struct (a[0].add(1)withArray<IB>,m["k"].prop = 4). Every index on the way to the element is evaluated once, first; then the arguments or the right-hand side; then the element is read (the element order in calls). Amutatingmethod runs on a copy of the element, and what it does to the element throughthisis stored back into the collection when it returns. While the method runs, changing that collection's value is a run-time error; reads are fine. A write counts whatever path it takes: a store into the same element (xs[0] = P(9, 9)) or another one, a swap, a removal of the element or of its map key,add,removeAt,remove, amutatingcall on another element of it, a replacement of the whole collection. The error is raised when the method returns: aRuntimeExceptionthat names the collection, the element and the remedy (copy the element out, call the method on the copy and store it back, or change the collection after the call). The write itself has happened, and the copy is dropped. A class instance held in a maybe-typed collection (below) is shared, so it keeps the changes the method made to it. A method that throws keeps its own exception: the copy is stored back when the collection was not written, and dropped when it was. The check compares the collection the place holds after the call with the one the element was read from. A call that leaves the place holding that very collection again (Array<P> s = xs; xs.add(p); xs = s;, orxs = xs) is therefore not detected, and nothing is lost: the copy is stored back into it. An equal-value write is no change of value either (xs[1] = xs[1], or storing aPequal to the one there, field by field, by their bits): no error, and the copy is stored back. A write to another collection is no error. Neither is a write to an outer collection that leaves the element's own collection in place (gq[1] = ..orgq[0].n = ..duringgq[0].rs[0].bump()), and nothing is lost by it: the copy is stored back intogq[0].rsas it is after the call. This changes behaviour for existing programs: such a write used to be overwritten by the element's copy, or to lose it. Asetaccessor run on an element (xs[0].prop = 5, an element'sset ([])) follows the same rule. Its window opens after the element's index has run, and the collection is read once there, so an index that writes the collection (xs[f()].prop = 5) is no error, as for a call. A hop on the way to the collection that reads through agetand yields an object, whose field the next hop reads, is a getter-only property, a static getter or a class-typed property with agetand aset(gg.h.ps[0].bump()withH get h(),S.viaS.ps[0].bump()). It roots the rest of the path in that object, as a call does (mk().ps[0].bump()). Its getter runs once for the call, and the element read, the check and the store-back all go through the object it returned. The check reads the collection again after the call. Through a field that the static type reads as a plain field but the running class overrides with agetaccessor, that getter runs once more. Through a property with both agetand asetthat yields the collection itself, or a struct holding it (h.ps[0].bump()withArray<P> get ps()/set ps(..)), the store is get, change, set: the getter runs for the read, again for the check and again for the store's get. A change to the value during the call (a replacement through the setter, an element store through the property, a store into the field behind it) raises before the set; otherwise the set writes the copy back. A getter that builds a fresh collection on every read raises nothing when nothing was written, because the two reads have the same value. An element of a maybe-typed collection (Array<IB>) is a place whatever it holds, so the rule holds also when it holds a class instance; an element ofArray<C>for a classCis shared, never copied, and is no such place. A struct reached through a method call is a temporary, soxs.at(0).bump()is a compile error. - The variable of a
forloop over an array of structs holds a copy of each element; writing to it, or calling amutatingmethod on it, leaves the array unchanged. - A field typed as an interface, or as a generic or optional type, is a place in the same way when it holds a struct: a
mutatingcall through it changes the stored value, also when that field is inside another struct (h.w.b.add(1)withstruct W { IB b; }, or a bareb.add(1)in a method ofW), and through any number of such fields, reached by.or?.(gs[i].w?.p?.m(a)andloc.w?.p?.m(a)withstruct S { W? w; }andstruct W { P? p; }): the call changes the struct in its place. A?.field that holdsNoneruns no argument and stores nothing; when an argument storesNoneinto such a field, the call does not run and nothing is stored. Below a property with agetand aset(d.pd.w?.p?.m(a),o.po?.q?.m(a)) the call is get, change, set: the getter once, the arguments, the call, the setter once;Noneat any hop runs the getter only. A store made to the field during the call wins: the call finishes on the value it started with, and the field keeps what was stored. - An index store into an element of an array or map whose element type is an interface, a generic or an optional type (
a[0][0] = 4withArray<IB>) runs the element'sset ([])and stores the element back, as for a struct element. An index store through a property with both agetand asetaccessor (h.b[0] = 4) reads the property, stores into what it read and passes the result to the setter: get, change, set. Through a property with only asetaccessor the store changes the field the property reads, which is then passed to the setter too. Through a property with only agetaccessor it changes the getter's value, a temporary, and nothing else, on every engine. Through a plain field of interface type it changes the stored struct in place, and a store the setter makes to that field wins (nothing is written back over it). The element's store-back also happens when the path reaches the collection through a class instance that a call or a?:yields (mk().a[0][0] = 4): the instance is shared. Amutatingcall or asetaccessor store through an element of a maybe-typed collection, or through a property with both agetand aset(a[0].add(1),m["k"].prop = 4,h.b.prop = 4,h.b.add(4),h.r.bump()), changes the collection or the property: get, change, set. A struct element reached through such a class instance is a place too (mk().ps[0].x = 3): a field store or amutatingcall on it changes the element in the shared object. - Storing a struct variable into an array literal (
[loc]) or withaddcopies it; the collection owns its own copy. - An array is a value:
Array<int> ys = xs;makesysan independent array, soys[0] = 99;does not changexs. Methods such asaddreturn a new array and leave the receiver unchanged. - A copy of a collection is shallow. An array of class instances copies the references, so both arrays still point at the same objects.
- A closure captures an object by reference, so mutations through it are shared. It captures a primitive local by value, and a
structor collection local the same way: the closure keeps its own copy, taken when the closure is created, so later changes to the variable are not seen by the closure. A write to that copy inside the closure is a compile error: assigning the captured variable, storing into a field or element of it, or calling amutatingmethod or a collection verb on it (cannot assign to captured 'n' in a lambda, seelang.primary-expressions). Return the new value instead, or (oncerefparameters land) take the variable as arefparameter. Which writes count goes by declared type: a store through a struct'sset ([])is one; amutatingcall or a collection verb on a captured value typed as an interface or an optional is an error too, whatever it holds, while one on a class-typed capture is allowed (the object is shared). A structthisinside a lambda in a struct method is captured by copy in the same way.
Examples
Arrays copy; the objects inside them do not:
Arrays are values, their elements may not be
use io::console;
class Counter {
int n = 0;
}
Array<int> xs = [1, 2, 3];
Array<int> ys = xs;
ys[0] = 99;
ys.add(4);
console.writeln(xs[0]);
console.writeln(xs.length());
console.writeln(ys.length());
Array<Counter> list = [Counter()];
Array<Counter> list2 = list;
list2[0].n = 4;
console.writeln(list[0].n);
1
3
4
4
A mutating call through an interface-typed field changes the stored value, also inside a struct:
A mutating call through an interface-typed field
use io::console;
interface IB {
mutating int add(int n);
int get();
}
struct B : IB {
int v;
new B(int a) { v = a; }
mutating int add(int n) { v = v + n; return v; }
int get() => v;
}
struct W {
IB b = B(1);
}
class H {
W w = W();
}
H h = H();
h.w.b.add(1);
console.writeln(h.w.b.get());
2
A closure captures an object live but a primitive by value:
A struct in a field or an array element is a place; a struct bound to a variable is a copy:
Mutating a struct through a field, a variable and an element
use io::console;
struct P {
int x;
int y;
mutating void bump() { x = x + 1; }
}
class H {
P p = P(1, 2);
}
void run() {
H h = H();
h.p.bump();
console.writeln(h.p.x);
P q = h.p;
q.bump();
console.writeln(q.x);
console.writeln(h.p.x);
Array<P> xs = [P(5, 6)];
Array<P> ys = xs;
xs[0].bump();
xs[0].y += 10;
console.writeln(xs[0].x);
console.writeln(xs[0].y);
console.writeln(ys[0].x);
}
run();
2
3
2
6
16
5
What a closure captures
use io::console;
class Box {
int v = 0;
}
void run() {
int seen = 0;
Box box = Box();
() => int inc = () => {
box.v = box.v + 1;
return seen + 1;
};
seen = inc();
seen = inc();
console.writeln(seen);
console.writeln(box.v);
}
run();
1
2
Notes
To share mutable state between a closure and its caller, put the state in a small class and capture the instance, not a local int: writing a captured int inside the closure is a compile error. Or return the new value from the closure and assign it outside.
See also
- Primitives (the object mask) — The built-in value types, their default values, the methods they carry, and the
voidunit rules.