我如何在nim中迭代ref对象的字段?



我有一个ref object类型,并希望遍历其所有字段并将它们回显出来。

这里有一个我想要的例子:

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

但是,这样做会导致编译器错误:

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)

浏览文档,似乎没有ref对象类型的迭代器,只有对象类型。如果是这种情况,那么如何遍历ref对象类型?

如果你想使用迭代器,你需要取消引用你想迭代的ref类型!这也可以适用于任何其他需要object参数,但您想与ref object实例一起使用的进程。

在nim中,取消引用操作符是[]

因此,为了工作,在迭代之前,ref对象类型Creature的实例x需要取消引用:

for fieldName, fieldValue in x[].fieldPairs:
echo fieldName

这也适用于您编写的任何过程,例如:

proc echoIter(val: object) =
for fieldName, fieldValue in val.fieldPairs:
echo fieldName
echoIter(x[])

最新更新