nim中表/类表集合中的任何类型



如何使表在Nim中具有键和值的任何类型?例如,下面的代码不能工作:

{"a": "string", "b": 4}

它说它期望(string, string),但得到(string, int),这意味着类型是从第一个元组确定的。由于泛型中的any类型是不允许的,我如何使它工作?

您可以使用以下方法(取自json模块):

import hashes, tables
type MyTypeKinds = enum
    MNil, MInt, MString
type MyGenericType = object
  case kind*: MyTypeKinds
  of MString:
    str*: string
  of MInt:
    num*: BiggestInt
  of MNil:
    nil
proc hash(mg: MyGenericType): Hash =
  case mg.kind:
  of MString:
    result = hash(mg.str)
  of MInt:
    result = hash(mg.num)
  of MNil:
    result = hash(0)
proc `==`(a: MyGenericType, b: MyGenericType): bool =
  if a.kind != b.kind:
    return false
  case a.kind:
  of MString:
    return a.str == b.str
  of MInt:
    return a.num == b.num
  of MNil:
    return true
var genericTable = initTable[MyGenericType, MyGenericType]()
var key, val: MyGenericType
key.kind = MString
key.str = "a"
val.kind = MInt
val.num = 4
genericTable[key] = val
echo genericTable[key].num

为了更好的可读性,你可能想实现类似json的%操作符。

这样,您仍然不能使用任何类型,只能使用一组预定义的类型,但这没关系,因为表要求类型具有散列过程。

EDIT:通过添加比较过程和修复错别字,使代码能够成功编译

#it is already in language core  : 
var Python_like_dic: openArray[(string, string)] = {"a": "string", "b": 4}

#iterations : 
for i in Python_like_dic : 
    echo i[0] , " = " , i[1]

最新更新