Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the type of a value as string?

Tags:

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 ) 
like image 569
OderWat Avatar asked Feb 05 '15 19:02

OderWat


People also ask

How do you return a string data type in Python?

To get the type of a variable in Python, you can use the built-in type() function. In Python, everything is an object. So, when you use the type() function to print the type of the value stored in a variable to the console, it returns the class type of the object.

How to Get type in C#?

The GetType() method of array class in C# gets the Type of the current instance. To get the type. Type tp = value. GetType();

How do you find the inside value of a string?

The valueOf() method returns the primitive value of a string. The valueOf() method does not change the original string. The valueOf() method can be used to convert a string object into a string.


2 Answers

Close, it's in the typetraits module:

import typetraits  var x = 12 echo x.type.name 
like image 68
def- Avatar answered Sep 20 '22 23:09

def-


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.

like image 30
JohnKoch Avatar answered Sep 21 '22 23:09

JohnKoch