0

When I try to create two objects, where the second object has a reference to the first, I get Error: invalid type: 'var Foo' in this context: 'Bar' for var:

type
  Foo = object
    x: int
  
type
  Bar = object
    foo: var Foo

var f = Foo(x: 10)
var b = Bar(foo: f)

https://play.nim-lang.org/#ix=3RG3

How do I get this to work?

congusbongus
  • 13,359
  • 7
  • 71
  • 99

2 Answers2

2

I think you need to create a ref Object for Foo. You can see plenty of examples for this in the sources (e.g. JsonNode and JsonNodeObj here), and is documented here and here.

type
  Foo = object of RootObj
    x: int
  FooRef = ref Foo

  Bar = object
    foo: FooRef

var f = FooRef(x: 10)
var b = Bar(foo: f)

f.x = 30
doAssert b.foo.x == 30

The suffix of the object is not mandatory, but the convention is to use Ref for the ref objects and Obj for value objects (naming conventions). E.g. you can write the above as:

type
  Foo = ref FooObj
  FooObj = object of RootObj
    x: int

  Bar = object
    foo: Foo

var f = Foo(x: 10)
var b = Bar(foo: f)

f.x = 30
doAssert b.foo.x == 30
xbello
  • 7,223
  • 3
  • 28
  • 41
1

The var keyword isn't valid in a type declaration context. If there is a need of nested mutable objects, you just need to declare the root one with var rather than with let, but not in the type declaration.

Here's how to do that:

type
  Foo = object
    x: int
  
type
  Bar = object
    foo: Foo

var f = Foo(x: 10)
var b = Bar(foo: f)

b.foo.x = 123

echo b
Davide Galilei
  • 484
  • 6
  • 9