'How do I create a mutable reference to an object in another object?
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?
Solution 1:[1]
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
Solution 2:[2]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Davide Galilei |
