Issue
I have a ref object
type and would like to iterate over all of its fields and echo them out.
Here an example of what I want:
type Creature* = ref object
s1*: string
s2*: Option[string]
n1*: int
n2*: Option[int]
n3*: int64
n4*: Option[int64]
f1*: float
f2*: Option[float]
b1*: bool
b2*: Option[bool]
var x = Creature(s1: "s1", s2: some("s2"), n1: 1, n2: some(1), n3: 2, n4: some(2.int64), f1: 3.0, f2: some(3.0), b1: true, b2: some(true))
for fieldName, fieldValue in x.fieldPairs:
echo fieldName
However, doing so causes this compiler error:
Error: type mismatch: got <Creature>
but expected one of:
iterator fieldPairs[S: tuple | object; T: tuple | object](x: S; y: T): tuple[
key: string, a, b: RootObj]
first type mismatch at position: 1
required type for x: S: tuple or object
but expression 'x' is of type: Creature
iterator fieldPairs[T: tuple | object](x: T): tuple[key: string, val: RootObj]
first type mismatch at position: 1
required type for x: T: tuple or object
but expression 'x' is of type: Creature
expression: fieldPairs(x)
Going through the documentation, there appear to be no iterators for ref object types, only for object types. If that's the case, then how do you iterate over ref object types?
Solution
If you want to use iterators, you need to de-reference the ref-type that you want to iterate over! This may also apply to any other proc that expects an object
parameter, but that you want to use with a ref object
instance.
In nim, the de-referencing operator is []
.
So in order to work, the instance x
of the ref object type Creature
needs to be de-referenced before iterating over it:
for fieldName, fieldValue in x[].fieldPairs:
echo fieldName
This will also work with any proc you write, for example like this:
proc echoIter(val: object) =
for fieldName, fieldValue in val.fieldPairs:
echo fieldName
echoIter(x[])
Answered By - Philipp Doerner Answer Checked By - Willingham (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.