Initial Commit
This commit is contained in:
706 files changed
+135430
No files matched your search
@@ -0,0 +1,56 @@
|
||||
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>): &pair { return v[0]; }
|
||||
def first_mut(v: &mut vector<pair>): &mut pair { return &mut v[0]; }
|
||||
|
||||
def main(): void {
|
||||
# `&` or `&mut` written binds the reference `at` gives, as with `at`.
|
||||
var numbers := vector::<i64>::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::<pair>::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::<string>::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::<u32, u32>::new(nothing {});
|
||||
counts.set(1, 10);
|
||||
var count := &mut counts[1];
|
||||
count = 11;
|
||||
val view := numbers.view();
|
||||
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}");
|
||||
}
|
||||
Reference in new issue
Block a user