How to get the type of a value as string?
Asked Answered
U

2

26

I would like to know if it is possible to get the type (int32 / float64 / string) from a value in Nim at runtime?

I thought this would be possible with the "typeinfo" library but I can't figure it out!

EDIT: Got an answer and made this real quick:

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

Output:

MyObject (
    a: int = 3
    b: int = 4
    s: string = abc
)
Udder answered 5/2, 2015 at 19:36 Comment(0)
C
26

Close, it's in the typetraits module:

import typetraits

var x = 12
echo x.type.name
Chuff answered 5/2, 2015 at 20:9 Comment(0)
J
4

You can use stringify operator $, which has a overloaded signature of

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

For example,

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

Note that nim manual encourages using typeof(x) instead of type(x),

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

Jacinthe answered 19/5, 2021 at 9:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.