import std::io; import std::containers; struct pair { var a: i64; var b: i64; } # `v[i]` is `v.at(i)`, so a function giving a reference gives the element itself. def first(v: &vector): &pair { return v[0]; } def first_mut(v: &mut vector): &mut pair { return &mut v[0]; } def main(): void { # `&` or `&mut` written binds the reference `at` gives, as with `at`. var numbers := vector::::new(); numbers.append(1); numbers.append(2); var by_at := &mut numbers.at(0); by_at = 10; var by_index := &mut numbers[1]; by_index = 20; println($"{numbers[0]} {numbers[1]}"); var pairs := vector::::new(); pairs.append(pair { a = 1, b = 2 }); val p := &mut pairs[0]; p.a = 5; first_mut(&mut pairs).b = 6; println($"{pairs[0].a} {first(&pairs).b}"); # Bound without `&`, an element is copied, and changes on its own after. val copy := pairs[0]; pairs[0].a = 7; println($"{copy.a} {pairs[0].a}"); # An element that owns what it holds is referred to, never copied. var names := vector::::new(); names.append(string::from("x", nothing {})); val name := &mut names[0]; name.append("y"); println($"{name} {names[0]}"); # A dictionary's value, and a view's element, are references too. var counts := dict::::new(nothing {}); counts.set(1, 10); var count := &mut counts[1]; count = 11; val view := numbers.span; val seen := view[0]; val lent := &view[0]; numbers[0] = 12; println($"{counts[1]} {seen} {lent}"); # A fixed array is indexed by the language, and its element is copied too. val held: u64[3] = [1, 2, 3]; var element := held[1]; element = 9; println($"{held[1]} {element}"); }