Structs in Nim
Go’s structs are typed collections of fields. They’re useful for grouping data together to form records.
This `person` struct type has `name` and `age` fields.
```nim
type
Person* = object
name: string
age: int
newPerson
constructs a new person object with the given name.
proc newPerson*(name: string): ref Person =
result = new(Person)
result.name = name
result.age = 42
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.
import strformat
echo Person(name: "Bob", age: 20)
You can name the fields when initializing an object.
echo Person(name: "Alice", age: 30)
Omitted fields will be zero-valued.
echo Person(name: "Fred")
An addr
prefix yields a pointer to the object.
echo Person(name: "Ann", age: 40).addr
It’s idiomatic to encapsulate new object creation in constructor functions.
echo newPerson("Jon")
Access object fields with a dot.
let s = Person(name: "Sean", age: 50)
echo s.name
You can also use dots with object pointers - the pointers are automatically dereferenced.
let sp = addr(s)
echo sp.age
Objects are mutable.
sp.age = 51
echo sp.age
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.
let dog = (name: "Rex", isGood: true)
echo dog
To run the program, save the code in structs.nim
and use nimble
or nim
to compile and run it.
$ nim c -r structs.nim
(Bob, 20)
(Alice, 30)
(Fred, 0)
(addr (Ann, 40))
(addr (Jon, 42))
Sean
50
51
((Rex, true))
Next example: Methods.