Learning Nim (4 Part Series)
var, let and const all of them are used to hold value in Nim, but there are slight differences that beginners need to be aware of.
var can be used in 3 different forms to define a variable.
# 1. Declare first and assign later. var <variable-name>: <variable-type> <variable-name> = <value> # 2. Declare and assign at the same time. var <variable-name>: <variable-type> = <value> # 3. Directly assign the variable, Nim compiler is smart # enough to guess the type of the value var <variable-name> = <value> # Following any case, the variable can be reassigned a value <variable-name> = <value>
# No var x = 9 x = "string" #throws type mismatch error
let also works like
let requires initialization and once the value is assigned, it cannot be changed.
let <variable-name>: <type> = <value> #works let <variable-name> = <value> #works let <variable-name>: <type> #ERROR <variable-name> = <value> #ERROR
let x = 9 let x = 10 #throws ERROR. It will be considered as redefinition of x.
const keyword is used if we want to assign a constant value to a variable and the value is known while writing the code. Once a value is assigned to it, it cannot be reassigned.
const <variable-name>: <type> = <value> #works const <variable-name> = <value> const <vaiable-name>: <type> #ERROR <variable-name> = <value> #ERROR
const and let are almost the same except that const expressions are evaluated at compile time and let expressions are evaluated at run time. For example:
var x = 9 let y = x+2 #works const z = x+2 #throws ERROR
The compiler needs an absolute value for a constant expression that can be bound to the variable at compile time.
If you learnt something, hit ❤️ and share. Others deserve learning too 🙂