example.mx raw
1 package main
2
3 import "moxie"
4
5 // Example Moxie file exercising syntax highlighting.
6 //
7 // Moxie is a TinyGo-derived systems language. Key differences from Go:
8 // - string and []byte are the same type
9 // - int and uint are always 32-bit
10 // - no goroutines; spawn() creates isolated domains over IPC
11 // - no new(), complex, uintptr; use &T{}, literal syntax, explicit pointers
12 // - text concat uses |, not +
13 // - fallthrough and go are compile errors
14
15 const MaxWorkers = 4
16
17 type Job struct {
18 id int32
19 name string
20 }
21
22 func worker(j moxie.Int32, out chan moxie.Int32) {
23 out <- moxie.Int32(int32(j) * int32(j))
24 }
25
26 func main() {
27 // Slice size literals: []T{:len} and []T{:len:cap}.
28 buf := []byte{:1024}
29 queue := []int32{:0:100}
30
31 // Channel and map literals replace make().
32 results := chan moxie.Int32{}
33 config := map[string]int32{
34 "timeout": 30,
35 "maxRetries": 3,
36 }
37
38 // Text concatenation with |, not +.
39 greeting := "hello " | "moxie" | "!"
40
41 // Fan out: each spawn creates an isolated domain.
42 for i := int32(0); i < MaxWorkers; i++ {
43 spawn(worker, moxie.Int32(i), results)
44 }
45
46 // Event loop.
47 for n := 0; n < MaxWorkers; n++ {
48 select {
49 case r := <-results:
50 println(int32(r))
51 }
52 }
53
54 /*
55 Range over text yields bytes, not runes.
56 Use an encoding library for rune-level iteration.
57 */
58 for i, b := range greeting {
59 if b == ' ' {
60 clear(buf[i:])
61 break
62 }
63 }
64
65 queue = append(queue, 1, 2, 3)
66 _ = config
67 }
68
69 // Multiple return values, generics.
70 func divide(a, b float64) (float64, error) {
71 if b == 0 {
72 return 0, nil
73 }
74 return a / b, nil
75 }
76
77 func filter[T any](items []T, pred func(T) bool) []T {
78 result := []T{:0:len(items)}
79 for _, item := range items {
80 if pred(item) {
81 result = append(result, item)
82 }
83 }
84 return result
85 }
86