When you have an object type variable, you cannot make ref objects to point it.
Unlike pointers, ref types cannot point to arbitrary memory location. It can
points to specific object created with `RefObjTypeName(param0: x)` or
[new](https://nim-lang.org/docs/system.html#new%2Cref.T) proc. I wrote about a
difference between ref object and plain object:
<https://internet-of-tomohiro.pages.dev/nim/faq.en#type-when-to-use-ref-object-vs-plain-object-qmark>
Example code:
type
Point = ref object
x, y: float
Triangle = ref object
points: array[3, Point]
Mesh = object
points: seq[Point]
triangles: seq[Triangle]
var mesh: Mesh
mesh.points.add Point(x: 0.0, y: 1.0)
mesh.points.add Point(x: 1.0, y: 0.0)
mesh.points.add Point(x: 0.0, y: 1.0)
var tri = Triangle(points: [mesh.points[0], mesh.points[1], mesh.points[2]])
mesh.triangles.add tri
echo mesh
Run
Or use index to indirectly refer objects in seq. Example code:
type
Point = object
x, y: float
Triangle = object
points: array[3, int]
Mesh = object
points: seq[Point]
triangles: seq[Triangle]
var mesh: Mesh
mesh.points.add Point(x: 0.0, y: 1.0)
mesh.points.add Point(x: 1.0, y: 0.0)
mesh.points.add Point(x: 0.0, y: 1.0)
var tri = Triangle(points: [0, 1, 2])
mesh.triangles.add tri
echo mesh
echo mesh.points[mesh.triangles[0].points[0]]
Run
`cast` and `addr` are unsafe features in Nim. They are rarely used unless you
use C libraries.