tonetheman's blog

small tutorial on objects and references in nim

You declare an object in nim with a type statement. This is very much the same as a struct in C/C++

# an object
type Person = object 
  name : string
  age : int

To create objects you use the name of object to create it. You can initialize variables or not.

# make an empty object
let p1 = Person()

# make an object with values
let p2 = Person(name: "tony", age:54)

# print it

To access a field contained in the object use the . to get the field value.

# access the age
echo("just the age:", p2.age)

nim has something called a traced reference. Presumably the traced part is referring to a garbage collector.

You declare a reference in a type section as seen below.

Once you have done that you can access the fields in the object that is pointed to with the . operator.

# make a new type that points to a Person
  pPerson = ref Person

# point pp2 to p2
let pp2 = p2

# print from the ref

# print a field from the ref
echo("just the age from ref", pp2.age)

- 0 toasts