Structs in Nim
newPerson
constructs a new person object with the given name.
Nim is a garbage collected language; you can safely return a pointer to a local variable - it will only be cleaned up by the garbage collector when there are no active references to it.
This syntax creates a new object.
You can name the fields when initializing an object.
Omitted fields will be zero-valued.
An addr
prefix yields a pointer to the object.
It’s idiomatic to encapsulate new object creation in constructor functions.
Access object fields with a dot.
You can also use dots with object pointers - the pointers are automatically dereferenced.
Objects are mutable.
If an object type is only used for a single value, we don’t have to give it a name. The value can have an anonymous object type. This technique is commonly used for table-driven tests.
To run the program, save the code in structs.nim
and use nimble
or nim
to compile and run it.
Next example: Methods.