module Mutable {
// MUTABLE TYPE BASICS
// data structures are immutable by default, but can be modified to be mutable by prefixing
// the type with mut. mutable data strutures are always reference types. see reference
// types for more info.
//
// immutable data types can not contain mutable data types.
//
// immutable data types may contain functions and interfaces, but they must be pure.
// see the section on pure for more info.
//
// immutable data types may not contain handles. see handles for more info.
//
// mutable data structures must be fully constructed before they can mutated.
// MUTABLE STRUCT
mut struct Velocity {
dx : int;
dy : int;
}
fn test1() {
let v = Velocity(1, 2);
v.dy += 1; // dy field of v may be updated because Velocity is marked mut
}
// MUTABLE TUPLE
fn test2() {
let v : mut (double, string) = (10.0, "px");
v.0 = 20.0; // v is (20.0, "px")
}
// MUTABLE VECTOR
fn test3() {
let v : mut int#3 = (0, 0, 0);
v.0 = 1.0; // v is (1, 0, 0)
}
// MUTABLE ARRAY
fn test4() {
let a : mut int[] = [1, 2, 3];
a[0] += 1; // a is now [2, 2, 3]
}
// MUTABLE MAP
fn test5() {
let m : mut Map{int,string} = {1 : "a", 2 : "b"};
m[3] = "c"; // m is now {1 : "a", 2 : "b", 3 : "c"}
}
// CONVERTING MUTABLE TO IMMUTABLE
fn test6() {
// Maps and Arrays have a take method which will produce an immutable copy
// and reset the data struture to empty. This method attempts to reuse the
// underlying memory used.
let m : mut int[] = [1, 2]; // m has 2 elements
let i : int[] = m.take(); // m has 0 elements, i has 2 elements
}
}