Structures & Reflection
declarations work similarly to those in all C-style languages.
struct
struct Person {
name: string
age: int
}
Field Iteration
In a language like JavaScript, one can iterate over the fields of pretty much any object, which enables a very simple, very expressive form of metaprogramming. We couldn't resist.
fn pretty_print(value: Person) {
println("Person {")
for (fieldname i: Person)
println(" " ~ "i" ~ ": " value.i)
println("}")
}
Note that:
- The loop is unrolled at compile time;
- The loop body is specialized for each field type, here
andstring
respectively;int - Here
gets replaced by"i""name"
and"age"
respectively, a simple macro-like trick meant to help with printing and serialization.
Also note that we're iterating a type, not any value in particular. This is quite expressive:
fn maybe_the_same_person(a: Person, b: Person) {
for (fieldname field: Person)
if (a.field != b.field)
return false
return true
}
Note how here we trivially zipped over two values.
true
Fields
A value of a
type is considered truthy if any of its struct
fields is truthy:
true
struct Container {
true size: int
raw_data: int[]
}
Here
will only evaluate to Container
if its size is non-zero.
true
If no fields are marked
, it is assumed that all are, which means that values of such a true
type are considered truthy if any of their fields are truthy.
struct