Just discovered nim I'm interested in IPC so looked at Marshal and tired to compile a tidbit there:
type
TA = object
TB = object of TA
f: int
var
a: ref TA
b: ref TB
new(b)
a = b
echo($$a[]) # produces "{}", not "{f: 0}"
I tired to compile it with 10.2 and got the following error:
wink-macbookpro2:x wink$ nim c -r y.nim
config/nim.cfg(45, 2) Hint: added path: '/Users/wink/.babel/pkgs/' [Path]
config/nim.cfg(46, 2) Hint: added path: '/Users/wink/.nimble/pkgs/nimble-0.6.0' [Path]
config/nim.cfg(46, 2) Hint: added path: '/Users/wink/.nimble/pkgs/' [Path]
Hint: used config file '/Users/wink/foss/nim/config/nim.cfg' [Conf]
Hint: system [Processing]
Hint: y [Processing]
y.nim(3, 14) Error: inheritance only works with non-final objects
So searched the net and apparently TA needs to be "inheritable":
type
TA {.inheritable.} = object
I recompiled then got a second error:
y.nim(12, 5) Error: undeclared identifier: '$$'
So I replaced '$$a[]' with '$a[]' in the echo statement and it worked:
/Users/wink/prgs/nim-pg/x/y
()
The "final" code is:
wink-macbookpro2:x wink$ cat y.nim
type
TA {.inheritable.} = object
TB = object of TA
f: int
var
a: ref TA
b: ref TB
new(b)
a = b
echo($a[]) # produces "{}", not "{f: 0}"
If my solution is "correct" I'd be happy to provide a patch to the documentation of lib/pure/marshal.nim.
You need to import marshal for $$ to work. $ is the string operator.
import marshal
type
TA {.inheritable.} = object
TB = object of TA
f: int
var
a: ref TA
b: ref TB
new(b)
a = b
echo($$a)
echo($$b)
That said, $$ does not seem to work correctly with inheritance regardless.
So I tried this:
import marshal
type
Person {.inheritable.} = object
age: int
name: string
Job = object of Person
title: string
var p = Person(age: 38, name: "Torbjørn")
var j: Job
j.age = p.age
j.name = p.name
j.title = "Programmer"
echo($$p)
echo($$j)
And the output is below, is this correct?
{"age": 38, "name": "Torbj\u00F8rn"}
{"title": "Programmer", "age": 38, "name": "Torbj\u00F8rn"}
Wink: And the output is below, is this correct?
That would seem to be correct. Note that while the serialized form does not include type information, that's derived during the unmarshaling process from the declared type of the result.