Examples · 15 of 339
15-values
Arrays and structs are values, like numbers.
tin run examples/15-values.tin// Arrays and structs are values, like numbers.
//
// Assigning, passing or capturing one gives you your own copy. Only a `var`
// can change in place, and a function can change the caller's variable only
// when its parameter says `inout`, and the call says `&`. So nothing changes
// behind your back.
type Robot = { name: string, joints: float[] }
/// Read-only: `r` is a value, and changing it is a compile error.
fn describe(r: Robot): string => "{r.name} with {r.joints.len} joints"
/// `inout`: changes the caller's var in place.
fn addJoint(r: inout Robot, angle: float) {
r.joints.push(angle)
}
fn main() {
var arm = Robot { name: "arm", joints: [0.0, 0.5] }
let snapshot = arm // a copy: later changes to arm don't reach it
let show = () => describe(snapshot)
addJoint(&arm, 1.25)
arm.joints[0] = 0.1
print(describe(arm)) // arm with 3 joints
print(show()) // arm with 2 joints
print(snapshot.joints[0]) // 0.0
var fleet = [arm, arm] // two independent robots
addJoint(&fleet[1], 2.0)
print("{fleet[0].joints.len} {fleet[1].joints.len}")
} arm with 3 joints
arm with 2 joints
0.0
3 4