如何将值的类型获取为字符串?

How to get the type of a value as string?

我想知道是否可以在运行时从 Nim 中的值中获取类型 (int32 / float64 / string)?

我认为 "typeinfo" 库可以做到这一点,但我想不通!

编辑:得到答案并很快完成:

import typetraits

type
    MyObject = object
        a, b: int
        s: string

let obj = MyObject(a: 3, b: 4, s: "abc")

proc dump_var[T: object](x: T) =
    echo x.type.name, " ("
    for n, v in fieldPairs(x):
        echo("    ", n, ": ", v.type.name, " = ", v)
    echo ")"

dump_var obj

输出:

MyObject (
    a: int = 3
    b: int = 4
    s: string = abc
)

关闭,在typetraits模块中:

import typetraits

var x = 12
echo x.type.name

您可以使用 stringify 运算符 $,它的重载签名为

proc `$`(t: typedesc): string {...}

例如,

doAssert $(42.typeof) == "int"

请注意 nim manual 鼓励使用 typeof(x) 而不是 type(x),

typeof(x) can for historical reasons also be written as type(x) but type(x) is discouraged.