如何在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对象类型似乎没有迭代器,仅针对对象类型。如果是这样,那么您如何迭代参考对象类型?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您想使用迭代器,则需要删除您想迭代的参考式!这也可能适用于任何其他期望
对象
参数的Proc,但您要与ref Ref Object
实例一起使用。在NIM中,删除参考运算符是
[]
。因此,为了工作,Ref Object类型的实例
x
creature
需要删除它,然后再迭代:这也将与您编写的任何Proc,例如这样:
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 aref object
instance.In nim, the de-referencing operator is
[]
.So in order to work, the instance
x
of the ref object typeCreature
needs to be de-referenced before iterating over it:This will also work with any proc you write, for example like this: