aboutsummaryrefslogtreecommitdiff
path: root/examples/struct_closure_opt.zc
diff options
context:
space:
mode:
authorGravatar Moon Flower <moonflower@elhenney.local> 2026-10-12 08:46:23 +0330
committerGravatar Moon Flower <moonflower@elhenney.local> 2026-10-12 08:46:23 +0330
commitecc350ca5c2eb50be8309c5f14f8bf0d87db9a02 (patch)
tree70e0af76a1b13affff7c6cc8aac7b3e6ef960478 /examples/struct_closure_opt.zc
a
Diffstat (limited to 'examples/struct_closure_opt.zc')
-rw-r--r--examples/struct_closure_opt.zc47
1 files changed, 47 insertions, 0 deletions
diff --git a/examples/struct_closure_opt.zc b/examples/struct_closure_opt.zc
new file mode 100644
index 0000000..67315bf
--- /dev/null
+++ b/examples/struct_closure_opt.zc
@@ -0,0 +1,47 @@
+// struct methods, closures and ownership in one file, written so the
+// compiler's hints have something to say about it. it runs as it is.
+
+struct point {
+ let x, y;
+
+ // methods get a hidden first parameter called this
+ fn dist(other) {
+ let dx = this.x - other.x;
+ let dy = this.y - other.y;
+ return dx * dx + dy * dy;
+ }
+}
+
+fn sink(.d p) { free(d*p); return 0; }
+
+fn features() {
+ // a closure copies the variables it uses when it is made
+ let base = 100;
+ let add = fn(a, b) { return a + b + base; };
+ let total = add(10, 20);
+
+ let p1 = new(point);
+ p1.x = 5; p1.y = 12;
+ let p2 = new(point);
+ p2.x = 0; p2.y = 0;
+
+ // made and given away on the next line, so it never needed a name
+ let tmp = new(2);
+ sink(d*tmp);
+
+ // allocated again on every pass of the loop
+ let i = 0;
+ while (i < 3) {
+ let scratch = new(10);
+ scratch[0] = i;
+ sink(d*scratch);
+ i++;
+ }
+
+ return total + p1.dist(p2);
+}
+
+fn main() {
+ put_n(features()); put_c(10);
+ return 0;
+}