Nim How to get Variable datatype with example?

This tutorial explains How to find the variable data type in Nim With examples

Nim typeof Operator Example

typeOf(variable) returns the datatype of a variable

Here is an examples

  • int type:
var number=12
echo typeOf(number) #int
  • Float types
var number1=12.123
echo typeOf(number1) #float64
  • char type:
var character='a'
echo typeOf(character) #char
  • String type:
var str="name"
echo typeOf(str) # string
  • Object type
Employee = object
id: int
name: string
echo typeOf(Employee) # Employee
  • bool
var isFlag = false;
echo typeOf(isFlag) # bool
  • sequence types
let sequence = @['a', 'b', 'c']
echo typeOf(sequence) # seq[char]

let numbers = @[1,2,3]
echo typeOf(numbers) # seq[int]

let numbers1 = @["one", "two"]
echo typeOf(numbers1) # seq[string]
  • Array types
var arr: array[3, int] = [7, 8, 9,]
echo typeof(arr) # array[0..2, int]
var arr1 = ["one", "two"]
echo typeof(arr1) # array[0..1, string]
  • Tuple types
let employee: tuple[name: string, id: int] = ("mark", 1)
echo typeof(employee) # tuple[name: string, id: int]

let employee: (string, int) = ("mark", 2)
echo typeof(employee) # (string, int)
  • Enum type
  WeekEnd = enum
    Saturday, Sunday
echo typeof(WeekEnd) # WeekEnd

How to check the Subtype of an object in Nim

Let’s create an object inheritance hierarchy of operator checks given object is a type or not, return true, else return false. Here is an example

type Employee = ref object of RootObj
name: string
id: int

type AdminEmployee = ref object of Employee

type SalesEmployee = ref object of Employee
var employees: seq[Employee] = @[]
employees.add(AdminEmployee(name: "one", id: 1))
employees.add(SalesEmployee(name: "two", id: 2))
echo(employees[0] of AdminEmployee) # true
echo(employees[1] of SalesEmployee) # true
echo(employees[0] of Employee) # true